使用 XPath、C# 解析 XML 文档 [英] Parsing XML document with XPath, C#

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

问题描述

所以我试图用 C# 解析以下 XML 文档,使用 System.XML:

So I'm trying to parse the following XML document with C#, using System.XML:

<root xmlns:n="http://www.w3.org/TR/html4/">
 <n:node>
  <n:node>
   data
  </n:node>
 </n:node>
 <n:node>
  <n:node>
   data
  </n:node>
 </n:node>
</root>

每篇关于命名空间的 XPath 论文都告诉我要做到以下几点:

Every treatise of XPath with namespaces tells me to do the following:

XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDoc.NameTable);
mgr.AddNamespace("n", "http://www.w3.org/1999/XSL/Transform");

在我添加上面的代码之后,查询

And after I add the code above, the query

xmlDoc.SelectNodes("/root/n:node", mgr);

运行良好,但没有返回任何内容.以下:

Runs fine, but returns nothing. The following:

xmlDoc.SelectNodes("/root/node", mgr);

如果我修改 XML 文件并删除命名空间,则返回两个节点,因此似乎其他所有内容都已正确设置.知道为什么它不适用于命名空间吗?

returns two nodes if I modify the XML file and remove the namespaces, so it seems everything else is set up correctly. Any idea why it work doesn't with namespaces?

非常感谢!

推荐答案

如前所述,重要的是命名空间的 URI,而不是前缀.

As stated, it's the URI of the namespace that's important, not the prefix.

给定您的 xml,您可以使用以下内容:

Given your xml you could use the following:

mgr.AddNamespace( "someOtherPrefix", "http://www.w3.org/TR/html4/" );
var nodes = xmlDoc.SelectNodes( "/root/someOtherPrefix:node", mgr );

这会给你你想要的数据.一旦你掌握了这个概念,它就会变得更容易,尤其是当你使用默认命名空间(源 xml 中没有前缀)时,因为你立即知道你可以为每个 URI 分配一个前缀并强烈引用你喜欢的文档的任何部分.

This will give you the data you want. Once you grasp this concept it becomes easier, especially when you get to default namespaces (no prefix in source xml), since you instantly know you can assign a prefix to each URI and strongly reference any part of the document you like.

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

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