Reading complex xml in C#

爷,独闯天下 提交于 2019-12-11 08:51:54

问题


i am trying to read an xml file, the format of the file as follow:

<rootnode>
<a>first<b>1st</b></a>
<a>second<b>2nd</b></a>
</rootnode>

i tried to use XDocument like this:

XDocument loadedData = XDocument.Load("file.xml");
        var data = from query in loadedData.Descendants("a")
                   select new myClass
                   {
                       Word = (string)query.Value,
                       secondWord = (string) query.Element("b")
                   };

but it didnt work, as the (string)query.Value will bring me the whole line;"first1st"

is there any way to get the text instead of the whole element?


回答1:


I'm not really in a position to do much exploration of the "correct" way to handle this in the XML, but how about if you did some string manipulation on the result?

 var data = from query in loadedData.Descendants("a")
     select new myClass
     {
         Word = (string)query.Value.Substring(0, ((string)query.Value).Length - ((string)query.Element("b").Value).Length),
         secondWord = (string)query.Element("b")
     };

Ugly, but it works. I'm sure there's a "better" way, but as I say, I don't have enough bandwidth to look into it at the moment.

EDIT

As I mentioned in a comment to the original question, if you are in control of writing the XML in the first place, it would be better to reformat it - possibly like this.

<rootnode>
  <item><a>first</a><b>1st</b></item>
  <item><a>second</a><b>2nd</b></item>
</rootnode>

Not only does this enable you to tidy up the code to get clean values, but allows flexibility to add more data items inside each element if needs be. e.g.

<rootnode>
  <item><a>first</a><b>1st</b><c>primary</c></item>
  <item><a>second</a><b>2nd</b><c>secondary</c></item>
</rootnode>



回答2:


You need to change your Descendants to be from "rootnode" rather than "a". Try this:

XDocument loadedData = XDocument.Load("file.xml");
var data = (from query in loadedData.Descendants("rootnode")
    select new myClass
    {
        Word  = (string)query.Element("a"),
        secondWord  = ((string)query.Element("b"))
    });


来源:https://stackoverflow.com/questions/6663607/reading-complex-xml-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!