【问题标题】:complex Xpath into Linq to XML复杂的 Xpath 到 Linq to XML
【发布时间】:2013-04-05 12:44:19
【问题描述】:

我的输入 XML:

....
    <node Attribute1 = "GUID1">
        <childnode1 AttributeChildnode= var1> </childnode>
        <childnode2 AttributeChildnode= var2> </childnode>
    </node>
    <node Attribute1 = "GUID2">
        <childnode3 AttributeChildnode= var3> </childnode>
        <childnode4 AttributeChildnode= var4> </childnode>
    </node>
....

我的 XPath 代码如下所示

mynodelist = xmldoc.SelectNodes(".//node[@Attribute1 ='" & varString1 &'']/nodechild[@AttributeChildnode1 = ''& varString2 &'']")

我不知道 Linq to XML 代码应该如何获得相同的结果 有人可以帮我吗

【问题讨论】:

    标签: xml linq linq-to-xml


    【解决方案1】:

    您仍然可以通过 XDocument 和 LINQ to XML 使用 XPath;

    var doc = XDocument.Load(filePath);
    var myNodeList = doc.XPathSelectElements(".//node[@Attribute1 ='" & varString1 &'']/nodechild[@AttributeChildnode1 = ''& varString2 &'']");
    

    XPathSelectElements 被声明为 XNode 上的扩展方法,在 System.Xml.XPath 命名空间内。

    标准 Linq to XML 版本

    输入 XML:

    <root>
        <node Attribute1="GUID1">
            <childnode AttributeChildNode1="var1" AttributeChildNode2="result1"></childnode>
            <childnode AttributeChildNode1="var2" AttributeChildNode2="result2"></childnode>
        </node>
        <node Attribute1="GUID2">
            <childnode AttributeChildNode1="var3" AttributeChildNode2="result3"></childnode>
            <childnode AttributeChildNode1="var4" AttributeChildNode2="result4"></childnode>
        </node>
    </root>
    

    查询:

    string guid = "GUID1";
    string var = "var1";
    
    var elements = XElement.Load("Input.txt");
    
    var value = (from node in elements.Elements("node")
                 where (string)node.Attribute("Attribute1") == "GUID1"
                 from childNode in node.Elements()
                 where (string)childNode.Attribute("AttributeChildNode1") == "var1"
                 select (string)childNode.Attribute("AttributeChildNode2")).FirstOrDefault();
    

    返回 result1 - result4,取决于 guidvar 变量值。

    【讨论】:

    • 没有 XpathSelectElements 也可以吗?前任。 dim var as IEnumerable(of Xelement) var = Select dummy from ....... where ..... select dummy
    • 我很确定是这样,但是您能发布输入 XML 和所需的输出吗?
    • Input code .... &lt;node Attribute1 = "GUID1"&gt; &lt;childnode1 AttributeChildnode= var1&gt; &lt;/childnode&gt; &lt;childnode2 AttributeChildnode= var2&gt; &lt;/childnode&gt; &lt;/node&gt; &lt;node Attribute1 = "GUID2"&gt; &lt;childnode3 AttributeChildnode= var3&gt; &lt;/childnode&gt; &lt;childnode4 AttributeChildnode= var4&gt; &lt;/childnode&gt; &lt;/node&gt; .... desired 输出可以是 var1,var2,var3 或 var4,具体取决于用户的选择。抱歉无法正确格式化文本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多