XElement属性值编码丢失,如何获取原始编码值?原因是什么?
如何获取XML解析中的原始编码值?
编码丢失的原因
咱们先搞明白为啥解析后编码值变了:当你用XElement.Parse()处理XML字符串时,.NET的XML解析器会自动解码XML实体引用——比如把&转换成&,<转换成<。
你的actualvalue是&lt;a&gt;,其实是对<a>的二次转义(先把<转成<,再把&转成&)。但XML解析器只会做一次解码,所以最终得到的是<a>,而不是你期望的原始二次转义字符串。这就是编码“丢失”的本质——不是真丢了,是解析器帮你做了一次实体转换。
解决方案(不用再次编码)
如果你想直接拿到原始的编码值,有两种靠谱的方法:
方法1:用XmlReader配置实体处理规则
通过设置XmlReaderSettings的EntityHandling为ReturnEntities,可以让解析器不自动解码实体,直接返回原始的字符串:
string abc = "<firstnode><secondnode abc=\"&lt;a&gt;\"></secondnode></firstnode>"; XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Ignore; // 关键配置:保留实体引用,不自动解码 settings.EntityHandling = EntityHandling.ReturnEntities; using (XmlReader reader = XmlReader.Create(new StringReader(abc), settings)) { reader.ReadToFollowing("secondnode"); string originalValue = reader.GetAttribute("abc"); // 此时originalValue就是你要的"&lt;a&gt;" }
方法2:用XElement API构建XML(避免手动拼接)
如果是你自己构建XML字符串,别手动拼接(容易踩实体转义的坑),直接用XElement的API创建。之后同样用XmlReader读取原始属性值:
string actualvalue = "&lt;a&gt;"; // 用API构建XML,避免手动拼接的转义问题 XElement item2 = new XElement("firstnode", new XElement("secondnode", new XAttribute("abc", actualvalue) ) ); // 通过XmlReader读取原始属性值 using (XmlReader reader = item2.CreateReader()) { reader.ReadToFollowing("secondnode"); string originalValue = reader.GetAttribute("abc"); // 同样得到"&lt;a&gt;" }
内容的提问来源于stack exchange,提问作者Ahtesham ul haq
相关产品推荐
相关产品推荐

