我正在嘗試使用 iXF 格式從 XML 檔案中獲取值,但我在使用 XPath 語法時遇到了一些問題。
我有以下 XML 檔案
<SOAP_ENV:Envelope xmlns:NS2="http://www.ixfstd.org/std/ns/core/classBehaviors/links/1.0" xmlns:NS1="CATIA/V5/Electrical/1.0" xmlns:tns="IXF_Schema.xsd" xmlns:ixf="http://www.ixfstd.org/std/ns/core/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP_ENV="http://schemas.xmlsoap.org/soap/envelope/" xsi:schemaLocation="IXF_Schema.xsd ElectricalSchema.xsd">
<SOAP_ENV:Body>
<ixf:object id="Electrical Physical System00000089.1" xsi:type="tns:Harness">
<tns:Name>Electrical Physical System00000089.1</tns:Name>
</ixf:object>
<ixf:object id="X10(1)//X11(1)" xsi:type="tns:Wire">
<tns:Name>X10(1)//X11(1)</tns:Name>
<NS1:Wire>
<NS1:Length>763,752mm</NS1:Length>
<NS1:Color>RD</NS1:Color>
<NS1:OuterDiameter>1,32mm</NS1:OuterDiameter>
</NS1:Wire>
</ixf:object>
</SOAP_ENV:Body>
</SOAP_ENV:Envelope>
我正在嘗試查找所有 Wire 物件并使用以下代碼獲取 Name 和 Length 值。
XmlDocument xlDocument = new XmlDocument();
xlDocument.Load(importFile);
XmlNamespaceManager nsManager = new XmlNamespaceManager(xlDocument.NameTable);
nsManager.AddNamespace("tns", "IXF_Schema.xsd");
nsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
nsManager.AddNamespace("ixf", "http://www.ixfstd.org/std/ns/core/1.0");
nsManager.AddNamespace("NS1", "CATIA/V6/Electrical/1.0");
nsManager.AddNamespace("NS2", "http://www.ixfstd.org/std/ns/core/classBehaviors/links/1.0");
//Get all wire objects
XmlNodeList wires = xlDocument.SelectNodes("descendant::ixf:object[@xsi:type = \"tns:Wire\"]", nsManager);
foreach (XmlNode wire in wires)
{
string wireName;
string wireLength;
XmlNode node = wire.SelectSingleNode("./tns:Name", nsManager);
wireName = node.InnerText;
XmlNode node1 = wire.SelectSingleNode("./NS1:Wire/NS1:Length", nsManager);
wireLength = node1.InnerText;
}
我可以毫無問題地獲得 wireName 值,但 Length 元素選擇總是回傳 0 個匹配項,我不知道為什么。我還嘗試使用與 Name 元素相同的語法僅選擇 Wire 元素,./NS1:Wire但它也回傳 0 個匹配項。
uj5u.com熱心網友回復:
您的 XML 宣告
xmlns:NS1="CATIA/V5/Electrical/1.0"
^^
你的 C# 宣告了一個不同的命名空間
nsManager.AddNamespace("NS1", "CATIA/V6/Electrical/1.0")
^^
確保兩個命名空間完全匹配。
關于您詢問在命名空間中使用版本號的評論......
不幸的是,在 XML 名稱空間中包含版本號是一種常見但肯定未被廣泛接受的做法。意識到這樣做,您實際上是在說每個命名空間的 XML 組件(元素或屬性)現在都應該被認為與舊命名空間中的對應部分不同。這很少是你想要的。
也可以看看
- 我應該使用 XML 檔案的命名空間來識別其版本嗎
- 對 XML 模式進行版本控制的最佳實踐是什么?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531621.html
標籤:C#xml路径
