例如
<reference>employee</reference>
<data>123</data>
如何使用c#解析,以便我应该获得employee和123作为输出
答案 0 :(得分:3)
您可以从中制作XML文档,然后解析它:
string info = "<reference>employee</reference><data>123</data>";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root>" + info + "</root>");
string reference = doc.DocumentElement.FirstChild.InnerText;
string data = doc.DocumentElement.FirstChild.NextSibling.InnerText;
另一种选择是使用正则表达式来解析字符串:
string info = "<reference>employee</reference><data>123</data>";
MatchCollection m = Regex.Matches(info, "<.+?>(.+?)</.+?>");
string reference = m[0].Groups[1].Value;
string data = m[1].Groups[1].Value;
或简单的字符串操作:
string info = "<reference>employee</reference><data>123</data>";
int start = info.IndexOf("<reference>") + 11;
string reference = info.Substring(start, info.IndexOf('<', start) - start);
start = info.IndexOf("<data>") + 6;
string data = info.Substring(start, info.IndexOf('<', start) - start);
答案 1 :(得分:1)
string xml = @"<root>
<reference>employee</reference>
<data>123</data>
</root>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xml);
string employee = doc.SelectSingleNode("reference").InnerText;
string data = doc.SelectSingleNode("data").InnerText;