2013-10-11 43 views
-1

我有一個完整的XML文檔,我成功地使用LINQ to XML進行導航。我有一個包含HTML的子節點,我想以字符串的形式獲取子節點的完整文本。獲取XML子元素和內容作爲文本

... 
<p> 
    this is sample text in <italic>italic</italic> and in <bold>bold</bold>. 
</p> 
... 

var text = node.Element("p").Value回報this is sample text in italic and in bold.

var text = node.Element("p").ToString()回報<p>this is sample text in <italic>italic</italic> and in <bold>bold</bold>.</p>

我真正想要的是this is sample text in <italic>italic</italic> and in <bold>bold</bold>.

什麼方法將內標籤作爲字符串一起返回內部文本?我不想要外部<p>標記。

+0

爲什麼向下票呢? – andleer

回答

1
var reader = node.Element("p").CreateReader(); 
reader.MoveToContent(); 
var inerXml = reader.ReadInnerXml(); 

OR

var inerXml = string.Concat(node.Element("p").Nodes().Select(x => x.ToString()).ToArray()); 
+0

我去尋找,但沒有看到它作爲Element()結果的屬性。 – andleer

+0

@andleer檢查我的更新 – Damith

+0

謝謝。經過一番搜索後,我自己想出了自己的想法。應該爲一個很好的擴展方法! – andleer

1

嘗試了這一點: -

您可以直接使用innerXml屬性來獲取p標籤作爲XML的內部內容。

namespace XML_Reader 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      XmlDocument xdoc = new XmlDocument(); 
      xdoc.Load("test.xml"); 
      XmlNode elem = xdoc.DocumentElement.FirstChild; 

      Console.WriteLine(elem.InnerXml);  
     } 
    } 
} 

XML: -

<element> 
    <p> 
    this is sample text in <italic>italic</italic> and in <bold>bold</bold>. 
    </p> 
</element> 

輸出: -

this is sample text in <italic>italic</italic> and in <bold>bold</bold>. 
+0

有趣的方法,但我不使用xdocs,而是使用Linq到XML。 – andleer

相關問題