首页 > 解决方案 > Xelement 属性值丢失其编码

问题描述

假设我们有这样的代码:

string actualvalue = "<a>";
string abc = "<firstnode><secondnode abc=\""+ actualvalue + "\"></secondnode></firstnode>";

XElement item2 = XElement.Parse(abc);
foreach (var item in item2.Descendants("secondnode"))
{
     string aftergettingitfromXlement = item.Attribute("abc").Value;
     ///so aftergettingitfromXlement  = "<a>" which is not correct i want to have actual value which is encoded 
}

知道如何获得实际值,我不想再次编码。为什么编码丢失了?

标签: c#encodingxelement

解决方案


试试这个:

string actualvalue = "&amp;lt;a&amp;gt;";

XDocument实现假定您的 xml 字符串中的值已转义。要阅读有关 xml 中的 escpae 字符的更多信息:我需要在 XML 文档中转义哪些字符?

要对字符串中的 & 符号进行一般替换,您可以编写:

string actualvalue = "&lt;a&gt;";
actualvalue = actualvalue.Replace("&", "&amp;");

推荐阅读