如何阅读XML在.NET? [英] How to Read XML in .NET?

查看:103
本文介绍了如何阅读XML在.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里XML小白!
所以,我有一些XML数据:

XML noob here! So I have some xml data:

<DataChunk>
    <ResponseChunk>
        <errors>
            <error code=\"0\">
                Something happened here: Line 1, position 1.
            </error>
        </errors>
    </ResponseChunk>
</DataChunk>

我该如何获得的错误在那里我可以访问错误code和下面的文字说明......名单?
另外,我使用.net4.0在C#...谢谢!

How would I get the a list of "errors" where I can get access to the "error code" and the text description following...? Also, I'm using .net4.0 in c#...thanks!

推荐答案

加载XML到的XmlDocument ,然后使用XPath查询来提取所需要的数据。

Load the XML into an XmlDocument and then use xpath queries to extract the data you need.

例如

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);

XmlNode errorNode = doc.DocumentElement.SelectSingleNode("/DataChunk/ResponseChunk/Errors/error");

string errorCode = errorNode.Attributes["code"].Value;
string errorMessage = errorNode.InnerText;

如果有是有,你可以使用多个错误元素的XML潜力的SelectNodes 来获得的XmlNodeList 包含在那个XPath的所有元素。例如:

If there is potential for the XML having multiple error elements you can use SelectNodes to get an XmlNodeList that contains all elements at that xpath. For example:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring);

XmlNodeList errorNodes = doc.DocumentElement.SelectNodes("/DataChunk/ResponseChunk/Errors/error");

foreach(XmlNode errorNode in errorNodes)
{
  string errorCode = errorNode.Attributes["code"].Value;
  string errorMessage = errorNode.InnerText;
}

选项2

如果您有XML,你可以在架构绑定到一个类(使用.NET xsd.exe工具)XML模式。一旦你有,你可以deserialise的XML转换成一个对象,并从该对象,而不是原始的XML使用它。这本身就是一个完整的主题,所以如果你有模式是值得研究的。

If you have a XML schema for the XML you could bind the schema to a class (using the .NET xsd.exe tool). Once you have that you can deserialise the XML into an object and work with it from that object rather than the raw XML. This is an entire subject in itself so if you do have the schema it is worth looking into.

这篇关于如何阅读XML在.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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