在 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
Parse XML document in C#
提问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 LoadXml
method.
或者,如果您在字符串中有 XML,请使用该LoadXml
方法。
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
加载后,您可以使用SelectNodes
和SelectSingleNode
查询特定值,例如:
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>