在 C# 中读取复杂的 xml
我正在尝试读取一个 xml 文件,该文件的格式如下:
<rootnode>
<a>first<b>1st</b></a>
<a>second<b>2nd</b></a>
</rootnode>
我尝试像这样使用 XDocument:
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")
};
但它不起作用,因为(字符串)query.Value 将为我带来整行;“first 1st”
有什么方法可以获取文本而不是整个元素?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我确实无法对在 XML 中处理此问题的“正确”方法做太多探索,但是如果您对结果进行一些字符串操作呢?
丑陋,但它有效。我确信有一种“更好”的方法,但正如我所说,我目前没有足够的带宽来研究它。
编辑
正如我在对原始问题的评论中提到的,如果您首先可以控制 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?
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.
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”而不是“a”。试试这个:
You need to change your Descendants to be from "rootnode" rather than "a". Try this: