首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 使用 XPath 查詢 InfoPath XML:條件篩選與巢狀節點實戰

     編輯:關於C語言

前言:InfoPath XML 的特殊結構

InfoPath 表單產生的 XML 具有深層巢狀、重複區塊(Repeating Section/Table)特性。常見需求:根據子節點條件篩選父層級項目,例如「找出所有 `c2='書'` 的項目對應的 `c1` 值」。

範例 XML 結構

<Table1>
  <a></a>
  <b></b>
  <c>          <!-- 重複群組 -->
    <c1>1</c1>
    <c2>書</c2>
    <c3>好</c3>
  </c>
  <c>
    <c1>2</c1>
    <c2>書</c2>
    <c3></c3>
  </c>
  <c>
    <c1>3</c1>
    <c2>書</c2>
    <c3>好</c3>
  </c>
  <c>
    <c1>4</c1>
    <c2>4</c2>
    <c3>4</c3>
  </c>
</Table1>

XPath 查詢技巧:相對路徑謂詞

關鍵在於使用 ..(父節點軸)在謂詞中向上導航,再向下選取兄弟節點。

單一條件:`c2 = '書'` 取 `c1`


// 方式 1:單引號包裹字串常值
IXMLDOMNodeList nodes = xdoc.DOM.SelectNodes("//Table1/b/c/c1[../c2 = '書']");

// 方式 2:雙引號需跳脫
IXMLDOMNodeList nodes = xdoc.DOM.SelectNodes("//Table1/b/c/c1[../c2 = \"書\"]");

解析:

  1. `//Table1/b/c` 定位到每個 `` 群組
  2. `/c1[../c2 = '書']`:從 `` 向上找父節點 ``,再向下找 `` 比較值
  3. 符合條件的 `` 節點被選中

多條件 AND:`c2='書' 且 c3='好'`


IXMLDOMNodeList nodes = xdoc.DOM.SelectNodes(
    "//Table1/b/c/c1[../c2 = '書' and ../c3 = '好']");

結果僅包含 `c1=1` 與 `c1=3` 兩個節點。

多條件 OR


// c2='書' 或 c2='筆'
IXMLDOMNodeList nodes = xdoc.DOM.SelectNodes(
    "//Table1/b/c/c1[../c2 = '書' or ../c2 = '筆']");

C# 完整程式碼範例


using System;
using System.Xml;
using System.Xml.XPath;
using MSXML2; // 需參考 Microsoft XML, v6.0 (msxml6.dll)

public class InfoPathXmlQuery
{
    public static void Main()
    {
        string xml = @"1書好
                                2書
                                3書好
                                444
                            ";

        var doc = new XmlDocument();
        doc.LoadXml(xml);

        // 使用 System.Xml.XPath (標準 .NET)
        var navigator = doc.CreateNavigator();
        var iterator = navigator.Select("//Table1/b/c/c1[../c2 = '書' and ../c3 = '好']");

        Console.WriteLine("符合 c2='書' 且 c3='好' 的 c1 值:");
        while (iterator.MoveNext())
        {
            Console.WriteLine(iterator.Current.Value); // 輸出: 1, 3
        }

        // 若在 InfoPath 表單程式碼中 (使用 MSXML DOM)
        // IXMLDOMNodeList list = thisXDocument.DOM.SelectNodes(...);
    }
}

XPath 軸速查

軸意義範例
`child::` / (預設)子節點`c/c1`
`parent::` / `..`父節點`../c2`
`ancestor::`所有祖先`ancestor::Table1`
`descendant::` / `//`所有後代`//c1`
`following-sibling::`後續同層節點`following-sibling::c2`
`preceding-sibling::`前序同層節點`preceding-sibling::c1`

常見坑點

  • 命名空間:InfoPath XML 通常有預設命名空間,XPath 查詢需註冊 `XmlNamespaceManager` 並使用前綴。
  • 編碼:確保 XML 載入時編碼正確(UTF-8),中文比對才不會失敗。
  • MSXML vs System.Xml:InfoPath Managed Code 環境用 `thisXDocument.DOM` (MSXML);獨立 .NET 應用建議用 `XmlDocument` + `XPathNavigator`。

總結

掌握 ../ 父節點軸在謂詞中的運用,是查詢 InfoPath 等巢狀重複結構 XML 的核心關鍵。配合 `and`/`or` 邏輯組合,即可靈活實現「依子節點條件篩選父群組」等進階查詢需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved