[英]How to select xml root node when root node has attribute?
我正在嘗試使用 XPath 查詢 select xml 文檔的根節點的所有子節點。
我的 xml 文件如下所示:
<?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# 代碼到 select 根節點如下:
XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNodeList allNodes = gazetteDocument.SelectNodes("root");
此代碼工作正常,當根節點沒有任何屬性時,它會選擇根節點的所有子節點,即它適用於第一個 xml 文件,但不適用於第二個 xml 文件,因為第二個文件具有 xmlns 屬性。
當根節點具有屬性時,有誰知道如何 select 根節點的所有子節點?
編輯:我發現了一個 XPath 查詢: /*
此查詢選擇根節點,無論它是否具有任何屬性。 一旦選擇了根節點,我就可以遍歷它的所有子節點。
盡管 XML 文檔中的命名空間很好,但您需要在SelectNodes
中使用它。 將此代碼用於您的第二個 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
和相應的類。 他們更容易使用。
您可以使用下面的 GetElementsByTagName 方法是我的代碼片段
XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNodeList allNodes = gazetteDocument.GetElementsByTagName("root");
我不知道 C# 的舊 xml 方法,但是您始終可以打開文件以讀取為普通文本,然后讀取到第一個節點並按照您的喜好進行解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.