我正在尝试根据DisplayOrder重新排序XML。我的XML是:
<ArrayOfCableItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CableItem>
<ItemID>6</ItemID>
<CableID>146242</CableID>
<FabID></FabID>
<Description>C</Description>
<ItemValue></ItemValue>
<Unit/>
<ItemComment/>
<Level>MET-JBOX J1</Level>
<Jack/>
<Type>Marker</Type>
<CableType>FreeForm</CableType>
<DisplayOrder>3</DisplayOrder>
</CableItem>
<CableItem>
<ItemID>540867</ItemID>
<CableID>146242</CableID>
<FabID>1398</FabID>
<Description>Routing</Description>
<ItemValue>27</ItemValue>
<ItemComment/>
<Type>Routing</Type>
<DisplayOrder>2</DisplayOrder>
</CableItem>
</ArrayOfCableItem>
我试过以下
XDocument output = new XDocument(new XElement("ArrayOfCableItem",
from s in xdoc.Root.Elements()
orderby Convert.ToInt32(s.Attribute("DisplayOrder").Value)
select s));
我试过这个,我不知所措
var reordered = xdoc
.Element("ArrayOfCableItem")
.Elements("CableItem")
.OrderBy(DO => Convert.ToInt32(DO.Attribute("DisplayOrder")));
XDocument doc2 = new XDocument(new XElement("ArrayOfCableItem"), reordered);
这些爆炸说加法操作可能导致格式错误的xml
答案 0 :(得分:1)
尝试如下所述,它正在运作。
查看评论以获取详细信息。
//LOAD THE XML
XDocument srcTree = XDocument.Load("C:\\Users\\<<USERID>>\\Desktop\\SampleXML.xml");
//CREATE NEW XML OUTPUT
XDocument doc = new XDocument(
//ROOT ELEMENT
new XElement("ArrayOfCableItem",
//FROM ALL ELEMENTS
from el in srcTree.Element("ArrayOfCableItem").Elements()
//ORDER BY "DISPLAYORDER" WHICH IS DESCENDANT ELEMENT
orderby (string)el.Descendants("DisplayOrder").First()
//SELECT THE ELEMENTS ORDERED
select el ));
//PRINT NEW XML IN CONSOLE
Console.WriteLine(doc);