簡體   English   中英

C#XPathSelectElements返回null?

[英]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循環不返回任何元素。 為什么?

這個對我有用。 檢查您的命名空間fxsd完全匹配。 在您的示例中,它們不匹配。 此外,您的示例中還有一些其他語法錯誤,例如,第二個formantsource-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM