在C#中解析XML文档 [英] Parse XML document in C#

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

问题描述

复制:这是最佳实践来解析XML文件和C#?以及许多其他(请参阅http://stackoverflow.com/search?q=c%23+parse+xml).请关闭它,不回答。

Duplicate: This is a duplicate of Best practices to parse xml files with C#? and many others (see http://stackoverflow.com/search?q=c%23+parse+xml). Please close it and do not answer.


如何从下向上解析XML文档中的C#?

How do you parse XML document from bottom up in C#?

例如:

<Employee>
   <Name> Test </name>
   <ID> 123 </ID>
<Employee>
<Company>
    <Name>ABC</company>
    <Email>test@ABC.com</Email>
 </company>

像这些有很多nodes..I需要开始从下向上解析解析like..first &LT;的公司和GT; ,然后等on..How DOI去这在C#?

Like these there are many nodes..I need to start parsing from bottom up like..first parse <company> and then and so on..How doi go about this in C# ?

推荐答案

试试这个:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

或者相反,如果你在一个字符串的XML使用的loadXML 方法。

Or alternatively if you have the XML in a string use the LoadXml method.

一旦你拥有了它加载,你可以使用的SelectNodes 的SelectSingleNode 查询特定的值,例如:

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "test@ABC.com"

最后,注意,XML是无效的,因为它不包含一个根节点。它必须是这样的:

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>test@ABC.com</Email>
    </Company>
</Data>

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

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