将 xml 字符串传递给 System.Xml.Linq.XElement 时,避免 xml 转义尖括号 [英] Avoid xml escaping of angle brackets, when passing xml string to System.Xml.Linq.XElement
问题描述
我从 string GetXmlString()
得到一个字符串;这是我无法改变的.
I'm getting a string from string GetXmlString()
; this I cant change.
我必须将其附加到 new XElement ("parent" , ... );
中的 xml,到 ...
区域.
I have to append this to an xml within a new XElement ("parent" , ... );
, to the ...
area.
我得到的这个字符串格式如下.
This string I'm getting is of the following format.
<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
...
我想要的最终结果是这样的
The final result I want is this to be like
<parent>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
...
</parent>
当我将字符串作为 XElement("root", GetXmlString()) 传递时
< 和 > 被编码为 <
和 >
when I just pass the string as XElement("root", GetXmlString())
< and > are encoded to <
and >
当我尝试 XElement.Parse(GetXmlString())
或 XDocument.Parse(GetXmlString())
我得到 有多个根元素强>异常.
When I try XElement.Parse(GetXmlString())
or XDocument.Parse(GetXmlString())
I get the There are multiple root elements exception.
如何在不转义括号的情况下获得所需的输出?我错过了什么?
How do I get the required output without escaping the brackets? What am I missing?
推荐答案
最简单的选择可能是给一个根元素,然后将其解析为 XML:
The simplest option is probably to give it a root element, then parse it as XML:
var doc = XDocument.Parse("<parent>" + text + "</parent>");
如果需要附加到现有元素,可以使用:
If you need to append to an existing element, you can use:
var elements = XElement.Parse("<parent>" + text + "</parent>").Elements();
existingElement.Add(elements);
这篇关于将 xml 字符串传递给 System.Xml.Linq.XElement 时,避免 xml 转义尖括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!