从指定字符串中提取子字符串的最佳和优化方法是什么。
我的主要字符串就像
string str = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>";
其中 AAA0 和 BBB1 的值是从某处收集的动态值。
我需要在这里提取 AAA0 和 BBB1。
请建议我是否有任何功能或优化方式来做到这一点。
谢谢你!
这绝对是低效的,但它可以满足您的要求。它假设周围 XML 的布局是不变的。
var foo = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>";
var ary = XDocument.Parse(foo).Root.Elements().ToArray();
// ary[1].Value -> AAA0
// ary[2].Value -> BBB1
使用 XmlDocument 的方法
void Main()
{
string str = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
var t = doc.GetElementsByTagName("t");
Console.WriteLine(t[1].InnerText);
Console.WriteLine(t[2].InnerText);
}