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

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

问题描述

这里是 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>

我如何获得错误"列表,我可以在其中访问错误代码"和下面的文本描述......?另外,我在 c# 中使用 .net4.0...谢谢!

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 来获取包含该 xpath 处所有元素的 XmlNodeList.例如:

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 的 XML 架构,您可以将架构绑定到一个类(使用 .NET xsd.exe 工具).一旦你有了它,你就可以将 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.

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

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