如何从xml响应中获取值

时间:2014-12-06 07:01:31

标签: c# xml

如何从以下xml响应中获取地址和网络掩码值

<?xml version="1.0" encoding="utf-8" ?> 
    - <controls>
      <ManualCalib>0</ManualCalib> 
      <MaintMode>0</MaintMode> 
      <AntEnable>0</AntEnable> 
      <ChgBeamEnable>1</ChgBeamEnable> 
      <ModemResponse>options show ETH0_1 [ETH0_1] address = 10.171.74.1 netmask = 255.255.255.0 rip_enabled = 0 [RMT:416] admin@telnet:::ffff:127.0.0.1;4709 ></ModemResponse> 
      </controls>

1 个答案:

答案 0 :(得分:0)

最好的解决方案是找出ModemResponse字符串的确切结构。您可以编写正则表达式来捕获所需的值,或者使用更强大的解析逻辑。如果您不知道确切的结构,可以编写一些像这样的hacky代码,以便在大多数情况下完成它:

        var xd = XDocument.Parse(xml);
        var modemResponse = xd.Element("controls").Element("ModemResponse").Value;
        string address = string.Empty, netmask = string.Empty;
        var tokens = modemResponse.Split(new[] { ' ', '=' }, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < tokens.Length; i++)
        {
            var token = tokens[i];
            switch (token)
            {
                case "address":
                    if (i + 1 < token.Length)
                        address = tokens[i + 1];
                    break;
                case "netmask":
                    if (i+1 < tokens.Length)
                        netmask = tokens[i+1];
                    break;
            }
        }

        Console.WriteLine("address: {0}, netmask: {1}", address, netmask);