如何从 XML 响应中获取值
本文关键字:获取 响应 XML | 更新日期: 2023-09-27 18:33:16
如何从以下 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>
最好的解决方案是找出调制解调器响应字符串的确切结构。您可以编写正则表达式来捕获所需的值,或者使用更可靠的解析逻辑。如果你不知道确切的结构,你可以写一些像这样的黑客代码来在大多数情况下完成它:
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);