c# - Ordering by attribute XML file with nested elements -


i order xml file, i'm having troubles in understanding how. noticed lot of suggestions similar case.

 var bookstore = xdoc.element("bookstore")             .elements("book")             .orderbydescending(s => (int) s.attribute("id"));  

my xml made this:

<?xml version="1.0" encoding="utf-8"?> <rank> <difficulty template="gamer">  <car type="formulaa" />  <car type="formulac" />  <car type="gt2" />  <car type="formulab" /> </difficulty> <difficulty template="racer">  <car type="formulaa" />  <car type="formulac" />  <car type="gt2" />  <car type="formulab" /> </difficulty> <difficulty template="pro">  <car type="formulaa" />  <car type="formulac" />  <car type="gt2" />  <car type="formulab" />  </difficulty> </rank> 

i modify final result similar one, write again same file.

<?xml version="1.0" encoding="utf-8"?> <rank> <difficulty template="gamer">  <car type="formulaa" />  <car type="formulab" />  <car type="formulac" />  <car type="gt2" /> </difficulty> <difficulty template="racer">  <car type="formulaa" />  <car type="formulab" />  <car type="formulac" />  <car type="gt2" /> </difficulty> <difficulty template="pro">  <car type="formulaa" />  <car type="formulab" />  <car type="formulac" />  <car type="gt2" />  </difficulty> </rank> 

i tried sort elements code, doesn't give me result want.

xdocument xdoc = xdocument.load(xmlfile); var orderedxmlfile = xdoc.descendants("car").orderby(s => (string)s.attribute("type"));  xdocument doc = new xdocument(new xelement("rank"), orderedxmlfile); doc.save(xmlfile); 

orderedxmlfile becomes list similar to

<car type="formulaa" /> <car type="formulaa" /> <car type="formulaa" /> <car type="formulab" /> <car type="formulab" /> <car type="formulab" /> <car type="gt2" /> <car type="gt2" /> <car type="gt2" /> 

and i'm unable save file. first time i'm trying modify xml files in c#, i'll gladly take advice or suggestions you'd want give me.

you're not trying order all car elements - you're trying order each group of elements. it's simplest use replacenodes each difficulty element:

foreach (var difficulty in xdoc.root.elements("difficulty")) {     difficulty.replacenodes(difficulty.elements()                                       .orderby(x => (string) x.attribute("type"))); } 

then save xdoc again.

this assumes don't mind modifying existing xdocument, of course.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -