繁体   English   中英

"XPathSelectElements 在带有命名空间的 XML 中总是返回空?"

[英]XPathSelectElements always return empty in XML with namespace?

我正在处理 XML 字符串,如下所示:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <Get_x0020_Remain_x0020_VacationResponse xmlns="http://tempuri.org/">
      <Get_x0020_Remain_x0020_VacationResult>
        <Period>0:0</Period>
        <Month>0:0</Month>
        <YearPeriod>16:0</YearPeriod>
        <YearMonth>32:0</YearMonth>
        <CurrentPeriod>0:0</CurrentPeriod>
        <CurrentMonth>14:0</CurrentMonth>
        <PeriodName>Davazdah</PeriodName>
        <MonthName>bahman</MonthName>
        <RemainUpToNowPeriod>0:0</RemainUpToNowPeriod>
        <RemainUpToNowMonth>0:0</RemainUpToNowMonth>
        <RemainUpToEndOfThisYearPeriodic>0:0</RemainUpToEndOfThisYearPeriodic>
        <RemainUpToEndOfThisYearMonthly>16:0</RemainUpToEndOfThisYearMonthly>
      </Get_x0020_Remain_x0020_VacationResult>
    </Get_x0020_Remain_x0020_VacationResponse>
  </soap:Body>
</soap:Envelope>

这包含在文档中:

XPath 将空前缀视为null名称空间。 换句话说,只有映射到命名空间的前缀才能在 XPath 查询中使用。 这意味着如果您要查询 XML 文档中的命名空间,即使它是默认命名空间,也需要为其定义前缀。

因此,如前所述,您需要添加前缀。 让我们说temp

xmlNamespaceManager.AddNamespace("temp", "http://tempuri.org/");

var nodeRemainUpToEndOfThisYearMonthly = 
     xDocument.XPathSelectElements("//temp:RemainUpToEndOfThisYearMonthly",
        xmlNamespaceManager);

我还要注意,除非您要使用它们,否则不需要添加任何其他前缀。

话虽如此,我建议仅使用 LINQ to XML API 更直接且类型安全:

XNamespace temp = "http://tempuri.org/";

var nodeRemainUpToEndOfThisYearMonthly = xDocument
    .Descendants(temp + "RemainUpToEndOfThisYearMonthly")
    .SingleOrDefault();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM