I have below XML file, and want to order the objects based on Revision Node and then write ordered objects back into XML file. I have tried LINQ but no luck
<?xml version="1.0" encoding="utf-8"?>
<v1:VNETList xmlns="http://www.xxxxxx.com/NET/eeim" xmlns:v1="http://www.xxxxxx.com/NET/List">
<Objects>
<ID>00-0000-PPP-0001 Template</ID>
<Object>
<ID>00-0000-PPP-0001</ID>
<Revision>2.0</Revision>
<Name>600-0000-PPP-0001</Name>
<ClassID>CL_Diagram</ClassID>
<Association type="is fulfilled by">
<Object>
<ID>aae9d_application/pdf</ID>
<Revision>2.0</Revision>
<ClassID>FILE</ClassID>
<Characteristic>
<Name>InfoType</Name>
<Value>pdf</Value>
</Characteristic>
</Object>
</Association>
<Characteristic>
<Name>Status</Name>
<Value>Historic</Value>
</Characteristic>
</Object>
<Object>
<ID>00-0000-PPP-0001</ID>
<Revision>3.0</Revision>
<Name>00-0000-PPP-0001</Name>
<ClassID>CL_Diagram</ClassID>
<Association type="is fulfilled by">
<Object>
<ID>090aaead_application/pdf</ID>
<Revision>3.0</Revision>
<ClassID>FILE</ClassID>
</Object>
</Association>
<Characteristic>
<Name>Transmittal Number</Name>
<Value>111111</Value>
</Characteristic>
<Characteristic>
<Name>Is PSI</Name>
<Value>yes</Value>
</Characteristic>
</Object>
<Object>
<ID>00-0000-PPP-0001</ID>
<Revision>1.0</Revision>
<Name>00-0000-PPP-0001</Name>
<ClassID>CL_Diagram</ClassID>
<Characteristic>
<Name>Is Confidential?</Name>
<Value>False</Value>
</Characteristic>
<Characteristic>
<Name>Is PSI</Name>
<Value>yes</Value>
</Characteristic>
</Object>
</Objects>
I want to order so revision 1 will come first, then 2 and the last will be three. Any help will be appreciated.
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement objects = doc.Descendants().Where(x => x.Name.LocalName == "Objects").FirstOrDefault();
XElement firstObject = objects.Elements().Where(x => x.Name.LocalName == "Object").FirstOrDefault();
XNamespace ns = firstObject.GetDefaultNamespace();
List<XElement> sortedObjects = objects.Elements(ns + "Object")
.OrderBy(x => (string)x.Descendants(ns + "Revision").FirstOrDefault())
.ToList();
objects.Elements(ns + "Object").Remove();
objects.Add(sortedObjects);
doc.Save(FILENAME);
}
}
}
you can sort the XML
using LINQ
XDocument inputxml = XDocument.Load(inputfile);
XDocument outputxml = new XDocument(
new XElement("Objects.Object",
from node in inputxml .Root.Elements()
orderby node.Element("Revision").Value
select node));
outputxml.Save(outputfile);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.