问题
Hi I need to create an XElement from a string, which can be xml or plain string.
This code
var doc = new XDocument(
new XElement("results", "<result>...</result>")
);
produces this
<results><result></result></results>
But if the string is XML, then I need proper XMl
<results><result>...</result></results>
Any ideas other than XElement.Parse() because it will throw exception if it is plain text?
回答1:
See my answer on Is there an XElement equivalent to XmlWriter.WriteRaw?
Essentially, replace a placeholder for the content only if you know it's already valid XML.
var d = new XElement(root, XML_PLACEHOLDER);
var s = d.ToString().Replace(XML_PLACEHOLDER, child);
This method may also be faster.
回答2:
I don't know if there is other way around and it also doesn't look as a best way but you can achieve it like this:
object resultContent;
if (condition)
{
//if content is XmlElement
resultContent = new XElement("result", "....");
}
else
{
resultContent = "Text";
}
XDocument xDoc = new XDocument(new XElement("results", resultContent));
回答3:
How about doing this:
XElement.Parse(String.Format("<Results>{0}</Results>",possibleXMLString));
... and before someone objects to this employing .Parse() method, which is mentioned by OP, please note that this is not the usage that was mentioned.
来源:https://stackoverflow.com/questions/16586443/adding-xml-string-to-xelement