繁体   English   中英

如何遍历XElements并使用C#比较值

[英]How to loop though XElements and compare values using C#

我有一个XElement,其中包含相似的节点但值不同。 就像我的XElement一样

<Information>
    <Emp>
        <A.EMPLID>1</A.EMPLID>
        <A.Phone>12##</A.Phone>
    </Emp>
    <Emp_Add>
        <B.ID>125</B.ID>
        <Add>XXXXXXX</Add>
    </Emp_Add>
    <Emp_Add>
        <B.ID>1256</B.ID>
        <Add>ZZZZZZ</Add>
    </Emp_Add>
</Information>

其实我需要经过各<Emp_Add>节点-回暖的值<B.ID>并将其与比较<Emp>.<A.EMPLID>值。 如果值相同,则使用C#代码显示消息"Values matched"否则显示消息"Values does not match"

如何在每个循环中使用XElement并进行比较。

我想你需要这样的东西

见我的dotnetfiddle

var xml =
                "<Information>\r\n\t<Emp>\r\n\t\t<A.EMPLID>1</A.EMPLID>\r\n\t\t<A.Phone>12##</A.Phone>\r\n\t</Emp>\r\n\t<Emp_Add>\r\n\t\t<B.ID>125</B.ID>\r\n\t\t<Add>XXXXXXX</Add>\r\n\t</Emp_Add>\r\n\t<Emp_Add>\r\n\t\t<B.ID>1256</B.ID>\r\n\t\t<Add>ZZZZZZ</Add>\r\n\t</Emp_Add>\r\n</Information>";
        var xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);
        XDocument xmlObj = XDocument.Parse(xmlDoc.OuterXml);

        var emplId = xmlObj.Descendants().Descendants().Descendants().FirstOrDefault().Value;
        var empsAdd = xmlObj.Descendants().Descendants().Where(d => d.Name.LocalName == "Emp_Add");
        foreach (var emp in empsAdd)
        {
            var currentEmpIdNode = emp.Descendants().FirstOrDefault();
            Console.WriteLine(currentEmpIdNode != null && currentEmpIdNode.Value == emplId
                              ? "Values matched"
                              : "Values does not match");
        }

暂无
暂无

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

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