2013-04-24 30 views
0

我有一個XML文檔:C#XPathSelectElements返回null?

<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循環不返回任何元素。爲什麼?

回答

2

它適合我。檢查您的名字空間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();