如何选择XML根节点时,根节点的属性? [英] How to select xml root node when root node has attribute?

查看:332
本文介绍了如何选择XML根节点时,根节点的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择使用XPath查询XML文档的根节点的所有子节点。

I am trying to select all the child nodes of root node of an xml document using XPath query.

我的XML文件看起来像下面这样:

My xml file looks something like following :

<?xml version="1.0" encoding="UTF-8" ?> 
<root>
    <automotive_industry>
        <automotive /> 
        <rail_global_services /> 
    </automotive_industry>
</root>

<?xml version="1.0" encoding="UTF-8" ?> 
<root xmlns="http://www.my_department.my_company.com/project_name">
    <automotive_industry>
        <automotive /> 
        <rail_global_services /> 
    </automotive_industry>
    </root>



C#代码选择根节点如下:

C# Code to select root node is as follows :

XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNodeList allNodes = gazetteDocument.SelectNodes("root");

此代码工作正常,它选择根节点的所有子节点时根节点没有任何属性是,它适用于第一个XML文件,但对于第二个xml文件不起作用,因为第二个文件有xmlns属性。

This code works fine, it selects all the child nodes of root node when root node does not have any attribute that is, it works for 1st xml file but does not work for 2nd xml file because 2nd file has xmlns attribute.

有谁知道如何选择所有的子节点根节点时,根节点的属性??

Does anyone knows how to select all the child nodes of root node when root node has attributes??

编辑:
我发现一个XPath查询: / * 此查询选择根节点,不管是否有任何属性或没有。一旦选择根节点,我可以通过它的所有子节点进行迭代。

EDIT : I found one XPath query : /* This query selects root node no matter whether it has any attribute or not. Once root node is selected, I can iterate through its all the child nodes .

推荐答案

虽然你的XML文档中的命名空间是好的,你需要在你的的SelectNodes 来使用它。
使用此代码对你的第二个XML:

Although the namespace in your XML document is fine, you need to use it in your SelectNodes. Use this code for your second XML:

XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(gazetteDocument.NameTable);
nsmgr.AddNamespace("ns", "http://www.my_department.my_company.com/project_name");
XmlNodeList allNodes = gazetteDocument.SelectNodes("ns:root", nsmgr);

更好的方法是使用的 的XDocument 和相应的课程。他们是一个更容易的工作。

The better way would be to use XDocument and corresponding classes. They are a lot easier to work with.

这篇关于如何选择XML根节点时,根节点的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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