[英]Avoid xml escaping of angle brackets, when passing xml string to System.Xml.Linq.XElement
I'm getting a string from string GetXmlString()
; 我从string GetXmlString()
得到一个字符串; this I cant change. 这我不能改变。
I have to append this to an xml within a new XElement ("parent" , ... );
我必须将此附加到new XElement ("parent" , ... );
的xml中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>
when I just pass the string as XElement("root", GetXmlString())
< and > are encoded to <
当我仅将字符串作为XElement("root", GetXmlString())
传递时XElement("root", GetXmlString())
<和>编码为<
and >
和>
When I try XElement.Parse(GetXmlString())
or XDocument.Parse(GetXmlString())
I get the There are multiple root elements exception. 当我尝试XElement.Parse(GetXmlString())
或XDocument.Parse(GetXmlString())
,出现“ 存在多个根元素”异常。
How do I get the required output without escaping the brackets? 我如何在不逃脱括号的情况下获得所需的输出? What am I missing? 我想念什么?
The simplest option is probably to give it a root element, then parse it as XML: 最简单的选择可能是给它一个根元素,然后将其解析为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);
An alternative to Jon's suggestion would be to create an XmlReader
for your fragment and parse from that: Jon建议的替代方法是为您的片段创建一个XmlReader
并从中进行解析:
var element = new XElement("parent");
var settings = new XmlReaderSettings
{
ConformanceLevel = ConformanceLevel.Fragment
};
var text = GetXmlString();
using (var sr = new StringReader(text))
using (var xr = XmlReader.Create(sr, settings))
{
xr.MoveToContent();
while (!xr.EOF)
{
var node = XNode.ReadFrom(xr);
element.Add(node);
}
}
This would be useful if the 'parent' element already exists, else simple concatenation of the XML nodes at each end and parsing would be simpler. 如果“父”元素已经存在,这将很有用,否则在两端的XML节点的简单串联和解析将更加简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.