簡體   English   中英

如何將字符串解碼為 C# 中的 XML 字符串

[英]How to decode string to XML string in C#

我有一個字符串(來自 CDATA 元素),其中包含 XML 的描述。 我需要將此字符串解碼為使用 C# 正確顯示字符的新字符串

現有字符串:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><myreport xmlns="http://test.com/rules/client"><admin><ordernumber>123</ordernumber><state>NY</state></report></myreport>

想要的字符串:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myreport xmlns="http://test.com/rules/client">
<admin><ordernumber>123</ordernumber><state>NY</state></report></myreport>

您可以使用System.Net.WebUtility.HtmlDecode而不是HttpUtility.HtmlDecode

如果您不想要System.Web參考並更喜歡System.Net ,則很有用。

  1. HttpUtility.HtmlDecode from System.Web
  2. 來自System.NetWebUtility.HtmlDecode

正如Kirillmsarchet所說,您可以使用HttpUtility.HtmlDecode中的System.Web 它幾乎可以正確地逃脫任何東西。

If you don't want to reference System.Web you might use some trick which supports all XML escaping but not HTML-specific escaping like &eacute;

public static string XmlDecode(string value) {
    var xmlDoc = new XmlDocument();
    xmlDoc.LoadXml("<root>" + value + "</root>");
    return xmlDoc.InnerText;
}

您也可以使用RegEx或簡單的字符串。 string.Replace ,但它只支持基本的 XML escaping。 &#x410; &eacute; 是更難支持的例子。

您可以使用HTML.Raw 這樣標記就不會被編碼。

您只需將轉義字符替換為其原始字符。

string stringWanted= existingString.Replace("&lt;", "<")
                                                   .Replace("&amp;", "&")
                                                   .Replace("&gt;", ">")
                                                   .Replace("&quot;", "\"")
                                                   .Replace("&apos;", "'");

HttpUtility.HtmlDecode(xmlString)將解決這個問題

您還可以考慮XDocument中的 static 解析方法。 我不確定它與這里提到的其他人相比如何,但它似乎很好地解析了這些字符串。

獲得生成的 XDocument 后,您可以使用 ToString 來獲取字符串:

string parsedString = XDocument.Parse("<My XML />").ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM