[英]C# XPathSelectElements returns null?
我有一個XML文檔:
<xsd:form-definition xmlns:xsd="http://...m.xsd"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="....xsd" ...>
<xsd:page>
<xsd:formant source-name="label" id="guid1" />
<xsd:formant source-name="label id="guid2" />
<xsd:formant source-name="label" id="guid3">
<xsd:value>2013-04-24</xsd:value>
</xsd:formant>
</xsd:page>
</xsd:form-definition>
並且通過C#代碼我想迭代特定元素並獲取id
屬性和value
(如果存在) - 讓我們說labels
。
為此,我嘗試了代碼
XDocument xml = (document load);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("f", "http://m.xsd");
foreach (XElement e in xml.XPathSelectElements("//f:formant[@source-name = 'label']", ns))
{
....
}
但foreach
循環不返回任何元素。 為什么?
這個對我有用。 檢查您的命名空間f
和xsd
完全匹配。 在您的示例中,它們不匹配。 此外,您的示例中還有一些其他語法錯誤,例如,第二個formant
的source-name
值不以雙引號結尾。
XDocument xml = XDocument.Parse(
@"<xsd:form-definition xmlns:xsd=""http://m.xsd""
xmlns:ds=""http://www.w3.org/2000/09/xmldsig#""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<xsd:page>
<xsd:formant source-name=""label"" id=""guid1"" />
<xsd:formant source-name=""label2"" id=""guid2"" />
<xsd:formant source-name=""label"" id=""guid3"">
<xsd:value>2013-04-24</xsd:value>
</xsd:formant>
</xsd:page>
</xsd:form-definition>");
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("f", "http://m.xsd");
foreach (XElement e in xml.XPathSelectElements(
"//f:formant[@source-name = 'label']", ns))
{
Console.WriteLine(e);
}
Console.ReadLine();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.