如何在XML中获取两个不同的节点值? [英] How to Get Two different nodes values in XML ?

查看:280
本文介绍了如何在XML中获取两个不同的节点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得两个节点值



XML



how to get two nodes values

XML

<Customers>
<quote id="1">
     <service>
       <name>Test value 1</name>
     </service>
     <rate>
       <amount>9510</amount>
     </rate>
   </quote>
   <quote id="2">
     <service>
       <name>Test value 2</name>
     </service>
     <rate>
       <amount>4515</amount>
     </rate>
</quote>
</Customers>





我必须尝试



C#代码





I have to try

C# code

string names="";
 
  XmlDocument doc = new XmlDocument();

        doc.LoadXml(result);

        XmlNodeList xnList = doc.SelectNodes("//Customers/quote/service");
       
        foreach (XmlElement xn in xnList)
        { 
            string NN = xn["name"].InnerText;
            if (NN != "")
            {
                names += NN + ",";                 
            }
        }
Response.write(names);





我得到了结果:



测试值1,测试值2





但我希望得到这样的结果



测试值1 @ 9510,测试值2 @ 4515





请帮助我



提前致谢



I got Result :

Test value 1,Test value 2


But i want to get result like this

Test value 1@9510,Test value 2@4515


Plese help me

Thanks in advance

推荐答案

var document = new XmlDocument();
document.LoadXml(result);

var nodes = document.SelectNodes("//Customers/quote");

string output = String.Empty;
for (int count = 0; count < nodes.Count; count++)
{
    var quote = nodes[count];
    if (quote != null)
    {
        var nameNode = quote.SelectNodes("service/name");
        if (nameNode != null)
        {
            output += nameNode[0].InnerText;
        }

        var amountNode = quote.SelectNodes("rate/amount");
        if (amountNode != null)
        {
            output = string.Format("{0}@{1}", output, amountNode[0].InnerText);
        }
    }

    output = string.Format("{0}, ", output);
}


您只需要查找报价中的下一个节点。例如。

You just need to look for the next node within the quote. E.g.
foreach (XmlElement xn in xnList)
{
    XmlNode xn2 = xn.SelectSingleNode("service/name");
    if (xn2 != null)
    {
        string NN = xn2.InnerText;
        if (NN != "")
        {
            names += NN;
            xn2 = xn.SelectSingleNode("rate/amount");
            string RR = xn2.InnerText;
            if(RR != "")
                names += "@" + RR;
            names += ",";
        }
    }
}


这篇关于如何在XML中获取两个不同的节点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆