--edit 我以后會擔心記憶體流,我如何先組合字串并列印輸出? - 編輯
字串 1 xml
<study-groups>
<study-group>
<name></name>
<uuid></uuid>
<href></href>
</study-group>
</study-groups>
xml字串2
<studies>
<study>
<name>someValue</name>
<uuid>someValue</uuid>
<href>someValue</href>
<parent-uuid>someValue</parent-uuid>
<created-at>2015-08-12T17:51:03Z</created-at>
<updated-at>2016-06-18T05:53:01Z</updated-at>
</study>
<study>
<name></name>
<uuid></uuid>
<href></href>
<parent-uuid></parent-uuid>
<created-at>2015-08-12T17:51:03Z</created-at>
<updated-at>2016-06-18T05:53:01Z</updated-at>
</study>
</studies>
我正在回圈通過 API HTTP 請求并將輸出 xml 保存到字串和記憶體流中。第一個 foreach 回圈生成一個 xml 檔案。在我的第二個回圈中,它回傳多個檔案。我想加入 string1 和 string2 以創建沒有重復的字串 3,并將字串 3 傳遞到每個回圈的第三個 4 中。
var xml1 = XDocument.Parse(string1);
var xml2 = XDocument.Parse(string2);
//Combine and remove duplicates
var string3 = xml1.Descendants("study-groups")
.Union(xml2.Descendants("studies"));
Console.WriteLine("---------------------string 3---------------------------");
Console.WriteLine(string3.ToString());
Console.WriteLine("---------------------string 3---------------------------");
//Combine and keep duplicates
var combinedWithDups = xml1.Descendants("study-groups")
.Concat(xml2.Descendants("studies"));
foreach (var i in combinedUnique)
{
Console.WriteLine("---------------------combinednodups---------------------------");
Console.WriteLine("{0}", i);
Console.WriteLine("---------------------combinednodups---------------------------");
}
但我的輸出不斷出現:
System.Linq.Enumerable UnionIterator2`1[System.Xml.Linq.XElement]
uj5u.com熱心網友回復:
如果問題只是輸出,那是因為呼叫ToString()an IEnumerable(像大多數型別一樣)只會列印型別的名稱。
相反,你可以這樣做:
// Join each element in the IEnumerable with a line break
Console.WriteLine(string.Join(Environment.NewLine, string3));
這將使用您的示例輸入生成以下內容:
<study-groups>
<study-group>
<name></name>
<uuid></uuid>
<href></href>
</study-group>
</study-groups>
<studies>
<study>
<name>someValue</name>
<uuid>someValue</uuid>
<href>someValue</href>
<parent-uuid>someValue</parent-uuid>
<created-at>2015-08-12T17:51:03Z</created-at>
<updated-at>2016-06-18T05:53:01Z</updated-at>
</study>
<study>
<name></name>
<uuid></uuid>
<href></href>
<parent-uuid></parent-uuid>
<created-at>2015-08-12T17:51:03Z</created-at>
<updated-at>2016-06-18T05:53:01Z</updated-at>
</study>
</studies>
但是,如果這就是您想要的,則無需使用XDocument. 您可以簡單地連接兩個字串:
var string3 = string1 Environment.NewLine string2;
Console.WriteLine(string3);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/515645.html
