简体   繁体   English

当根节点具有属性时,如何 select xml 根节点?

[英]How to select xml root node when root node has attribute?

I am trying to select all the child nodes of root node of an xml document using XPath query.我正在尝试使用 XPath 查询 select xml 文档的根节点的所有子节点。

My xml file looks something like following:我的 xml 文件如下所示:

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

AND

<?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# Code to select root node is as follows: C# 代码到 select 根节点如下:

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

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.此代码工作正常,当根节点没有任何属性时,它会选择根节点的所有子节点,即它适用于第一个 xml 文件,但不适用于第二个 xml 文件,因为第二个文件具有 xmlns 属性。

Does anyone knows how to select all the child nodes of root node when root node has attributes??当根节点具有属性时,有谁知道如何 select 根节点的所有子节点?

EDIT: I found one XPath query: /* This query selects root node no matter whether it has any attribute or not.编辑:我发现了一个 XPath 查询: /*此查询选择根节点,无论它是否具有任何属性。 Once root node is selected, I can iterate through its all the child nodes.一旦选择了根节点,我就可以遍历它的所有子节点。

Although the namespace in your XML document is fine, you need to use it in your SelectNodes .尽管 XML 文档中的命名空间很好,但您需要在SelectNodes中使用它。 Use this code for your second XML:将此代码用于您的第二个 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);

The better way would be to use XDocument and corresponding classes.更好的方法是使用XDocument和相应的类。 They are a lot easier to work with.他们更容易使用。

You can use GetElementsByTagName method below are the snippet of my code您可以使用下面的 GetElementsByTagName 方法是我的代码片段

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

I don't know the old xml methods of C#, but you could always open the file to read as normal text, and then read to the first node and parse it however you like.我不知道 C# 的旧 xml 方法,但是您始终可以打开文件以读取为普通文本,然后读取到第一个节点并按照您的喜好进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM