从xml片段中删除html标签?
问题描述:
我正在寻找从下面的代码片段去掉HTML标签。这是一个示例,XML文件架构可以更改,XML也是如此,并且不是静态的。 我想保留XML节点 有没有办法自动做到这一点,而无需使用外部库/工具/等?从xml片段中删除html标签?
<house>
<welcome>This is a <b>great</b> house.</welcome>
</house>
答
我建议
string yourXml = ".....";
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(yourXml);
string yourXmlWithoutTags = xmlDoc.InnerText;
string someContentWithoutTags = xmlDoc.SelectSingleNode("root/house").InnerText;
等等
+0
不幸的是,这个xml不是stactic,并且可以有与上面提到的不同的结构,所以这个解决方案将不起作用 – Idothisallday
答
虽然我主张用HTML Agility Pack为HTML,根据你的榜样,的XDocument翻出HTML没有问题。
var xmlString = @"<house>
<welcome>This is a <b>great</b> house.</welcome>
</house>";
var xml = XDocument.Parse(xmlString);
var welcome = xml.Descendants("house").Elements("welcome").First().Value;
Console.Write(welcome);
//This is a great house.
这可能是因为当Parse
发生时,<b>
删除标记。 Load
不会有这种行为。
的HTML敏捷包的方法将是这个样子:
public string StripTags(string input) {
var doc = new HtmlDocument();
doc.LoadHtml(input ?? "");
return doc.DocumentNode.InnerText;
}
+0
解析有点有趣。让我探索这个选项。 – Idothisallday
这很可能是这会使用'Replace'与'HTML'标签一长串涉及。 –
@MartinParkin这是我的想法......但想知道肯定没有其他办法。谢谢 – Idothisallday
这出现一次又一次。使用XDocument解析XML,然后像HTML一样处理HTML并使用HTML Agility Pack。 – paqogomez