在 C# 中解析 XML 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1238528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:03:38  来源:igfitidea点击:

Parse XML document in C#

c#xml

提问by GIRISH GMAIL

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

重复:这是使用 C# 解析 xml 文件最佳实践的重复和许多其他人(见https://stackoverflow.com/search?q=c%23+parse+xml)。请关闭它,不要回答。



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

你如何在 C# 中自下而上解析 XML 文档?

For Example :

例如 :

<Employee>
   <Name> Test </name>
   <ID> 123 </ID>
<Employee>
<Company>
    <Name>ABC</company>
    <Email>[email protected]</Email>
 </company>

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# ?

像这些有很多节点..我需要从下往上开始解析,比如..首先解析<company>然后等等..如何在 C# 中解决这个问题?

回答by Jon Grant

Try this:

尝试这个:

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

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

或者,如果您在字符串中有 XML,请使用该LoadXml方法。

Once you have it loaded, you can use SelectNodesand SelectSingleNodeto query specific values, for example:

加载后,您可以使用SelectNodesSelectSingleNode查询特定值,例如:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

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

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

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>