在C#中读取复杂的xml [英] Reading complex xml in C#

查看:735
本文介绍了在C#中读取复杂的xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取xml文件,该文件的格式如下:

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>

我试图这样使用XDocument:

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")
                   };

但是它没有用,因为(string)query.Value将带给我整行;"first 1st "

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?

推荐答案

我实际上不能对XML中处理此问题的正确"方式进行过多探索,但是如果您做了一些字符串怎么办?操纵结果?

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.

编辑

正如我在对原始问题的评论中提到的那样,如果您一开始就可以控制XML的编写,则最好对其进行重新格式化-可能像这样.

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>

这篇关于在C#中读取复杂的xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆