我有一个XML文件,如下所示:
<sections>
<section name="516604">
<item key="Terminal" value="254726387322" />
<item key="UserName" value="SomeName" />
<item key="Pass" value="XXXX" />
</section>
<section name="802200">
<item key="Terminal" value="254726402010" />
<item key="UserName" value="SomeOtherName" />
<item key="Pass" value="XXXX" />
</section>
</sections>
如何使用C#函数返回包含字段值的字符串,如下所示:
public string GetXMLValue(string Section, string Terminal)
{
return string TerminalOfSection
}
上述方法应该返回XML Tag值&#34; Terminal&#34;给定部分说&#34; 516604&#34;作为一个字符串。
谢谢。
我对XML做了一些修改以达到我的目的:
<xml version="1.0" encoding="UTF-8"?>
<516604>
<Terminal>254726387322</Terminal>
<UserName>SomeUser</UserName>
<Pass>XXXX</Pass>
</516604>
<802200>
<Terminal>254726402010</Terminal>
<UserName>SomeOtherUser</UserName>
<Pass>XXXX</Pass>
</802200>
以下是从XML获取确切标记并将其保存在字符串中的代码:
public static string GetXMLValue(string XMLSection, string XMLInput, string XMLtagValue)
{
string retval = string.Empty, FirstXMLSection = string.Empty, LastXMLSection = string.Empty,
FirstXMLtagValue = string.Empty, LastXMLtagValue = string.Empty;
//Tag the XML section to retrieve value from
FirstXMLSection = "<" + XMLSection + ">";
LastXMLSection = "</" + XMLSection + ">";
//Tag the XML element to retrieve value from
FirstXMLtagValue = "<" + XMLtagValue + ">";
LastXMLtagValue = "</" + XMLtagValue + ">";
if (XMLInput.IndexOf(XMLtagValue) != -1)
{
//Retrieve XML Section & save in a string retval
retval = XMLInput.Substring(XMLInput.IndexOf(FirstXMLSection));
retval = retval.Substring(FirstXMLSection.Length);
retval = retval.Substring(0, retval.IndexOf(LastXMLSection));
//Retrieve XML element & still save in a string retval
retval = retval.Substring(retval.IndexOf(FirstXMLtagValue));
retval = retval.Substring(FirstXMLtagValue.Length);
retval = retval.Substring(0, retval.IndexOf(LastXMLtagValue));
}
return retval;
}
因此,如果我将部分作为516604提供,则XML Text as XMLInput&amp;终端作为Tag获取Value的输出 将是:254726387322。欢迎任何改进/缺点。感谢。