2014-02-25 191 views
0

我正在尋找從下面的代碼片段去掉HTML標籤。這是一個示例,XML文件架構可以更改,XML也是如此,並且不是靜態的。 我想保留XML節點 有沒有辦法自動做到這一點,而無需使用外部庫/工具/等?從xml片段中刪除html標籤?

<house> 
    <welcome>This is a <b>great</b> house.</welcome> 
</house> 
+0

這很可能是這會使用'Replace'與'HTML'標籤一長串涉及。 –

+0

@MartinParkin這是我的想法......但想知道肯定沒有其他辦法。謝謝 – Idothisallday

+0

這出現一次又一次。使用XDocument解析XML,然後像HTML一樣處理HTML並使用HTML Agility Pack。 – paqogomez

回答

0

我建議

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

0

雖然我主張用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