数据是正确的 xml,还是只是看起来像?
如果是 html,那么 HTML Agility Pack 值得研究——它提供了一个 DOM(类似于 XmlDocument),您可以使用它来查询数据:
string input = @"<html>...some html content <b> etc </b> ...
<user> hello <b>mitch</b> </user>
...some html content <b> etc </b> ...
<message> some html <i>message</i> <a href....>bla</a> </message>
...some html content <b> etc </b> ...</html>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(input);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//user | //message"))
{
Console.WriteLine("{0}: {1}", node.Name, node.InnerText);
// or node.InnerHtml to keep the formatting within the content
}
这个输出:
user: hello mitch
message: some html message bla
如果您想要格式化标签,请使用 .InnerHtml 而不是 .InnerText。
如果是 xml,那么要使用 xml 的全谱进行编码,最好使用 xml 解析器。对于中小型 xml,将其加载到诸如 XmlDocument 之类的 DOM 中就可以了 - 然后查询节点(例如,“//*”)。对于大型 xml,XmlReader 可能是一种选择。
如果数据不必担心完整的xml,那么一些简单的正则表达式应该不会太棘手......一个简化的例子(没有属性,没有命名空间,没有嵌套的xml)可能是:
string input = @"blah <tag1> content for tag 1 </tag1> blop
<tag2> content for tag 2 </tag2> bloop
<tag3> content for tag 3 </tag3> blip";
const string pattern = @"<(\w+)>\s*([^<>]*)\s*</(\1)>";
Console.WriteLine(Regex.IsMatch(input, pattern));
foreach(Match match in Regex.Matches(input, pattern)) {
Console.WriteLine("{0}: {1}", match.Groups[1], match.Groups[2]);
}