2016-08-18 280 views
-1

我試圖解析我的xml,它有一個CData標記作爲其節點的值。我的XML結構如下。從C#中解析XML中的CData

<node1> 
<node2> 
<![CDATA[ <[email protected]@@BREAK TYPE="TABLE" @@@--> <P><CENTER>... html goes here.. ]]> 
</node2> 
</node1> 

我的代碼如下。當我解析時,我得到了CData標籤的響應,而不是CData標籤中的值。你能幫我解決我的問題嗎?

XDocument xmlDoc = XDocument.Parse(responseString); 
XElement node1Element = xmlDoc.Descendants("node1").FirstOrDefault(); 
string cdataValue = node1Element.Element("node2").Value; 

Actual Output: <![CDATA[ <[email protected]@@BREAK TYPE="TABLE" @@@--> <P><CENTER>... html goes here.. ]]> 

Expected Output: <[email protected]@@BREAK TYPE="TABLE" @@@--> <P><CENTER>... html goes here.. 

我不確定System.XML.Linq.XDocument是否導致問題。所以我嘗試了XMLDocument版本如下。

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml(responseString); 
XmlNode node = xmlDoc.DocumentElement.SelectSingleNode(@"/node1/node2"); 
XmlNode childNode = node.ChildNodes[0]; 
if (childNode is XmlCDataSection) 
{} 

而我的if循環返回false。所以看起來像我的XML有什麼問題,它實際上不是一個有效的CData?請幫我解決這個問題。 請讓我知道你是否需要更多的細節。

+0

是否有理由解答此問題?我試圖確保我提供所有必要的信息。 – csharpnewbie

回答

-1

這是因爲StreamReader是轉義的HTML。所以「<」變爲"&lt;"。因此它不能被正確識別爲cdatatag。所以不得不先做unescape - XDocument xmlDoc = XDocument.Parse(HttpUtility.HtmlDecode(responseString))

並且修復了它。

3

你所描述的內容永遠不會發生。將包含cdata的節點的Value作爲子節點將爲您提供內部文本cdata的內容。您應該已經獲得了您的預期輸出。

你可以得到實際的cdata節點的唯一方法是,如果你實際上得到了cdata節點。

​​3210
+0

但是,這是輸出,我不知道如果我錯過了明顯的東西。因此我想在這裏與同行進行覈對。我知道我應該得到cdata的內容,但我不知道。 – csharpnewbie

+0

首先,嘗試重現問題而不從某些響應中獲取數據。使用該響應的內容創建一個字符串,並在單獨的程序中通過代碼運行該字符串。你不會得到你所說的話。如果你以某種方式做,那麼這意味着你的輸入字符串是_not_你在這裏發佈的內容。發佈該字符串,如果它符合你說的話。 –

+0

帶字符串的獨立控制檯程序工作得非常好,並按預期生成結果 - 只是cdata標記內的文本。但是當我用服務器的響應運行我的實際代碼時,它不能正常工作。 – csharpnewbie

0

我試過你的代碼和CData值是正確的......?!?

你如何填寫你的reponseString? :-)

static void Main(string[] args) 
{ 
    string responseString = "<node1>" + 
          "<node2>" + 
          "<![CDATA[ <[email protected]@@BREAK TYPE=\"TABLE\" @@@--> <P><CENTER>... html goes here.. ]]>" + 
          "</node2>" + 
          "</node1>"; 

    XDocument xmlDoc = XDocument.Parse(responseString); 
    XElement node1Element = xmlDoc.Descendants("node1").FirstOrDefault(); 
    string cdataValue = node1Element.Element("node2").Value; 

    // output: <[email protected]@@BREAK TYPE=\"TABLE\" @@@--> <P><CENTER>... html goes here.. 
} 
+0

@MarxKlaxx,這是因爲StreamReader正在轉義html。所以「<」變成了「<」。所以不得不先做unescape - XDocument xmlDoc = XDocument.Parse(HttpUtility.HtmlDecode(responseString))並修復它。 – csharpnewbie