我正在寻找将包含有效XML的字符串转换为C#中的XmlElement
对象的最简单方法。
你如何将其转换为XmlElement
?
<item><name>wrench</name></item>
我正在寻找将包含有效XML的字符串转换为C#中的XmlElement
对象的最简单方法。
你如何将其转换为XmlElement
?
<item><name>wrench</name></item>
使用这个:
private static XmlElement GetElement(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return doc.DocumentElement;
}
注意!如果您需要将此元素添加到另一个文档中,首先需要使用ImportNode
导入它。
<?xml
不是必需的。 - dtb假设您已经有了一个带有子节点的XmlDocument,现在需要从字符串中添加更多的子元素。
XmlDocument xmlDoc = new XmlDocument();
// Add some child nodes manipulation in earlier
// ..
// Add more child nodes to existing XmlDocument from xml string
string strXml =
@"<item><name>wrench</name></item>
<item><name>screwdriver</name></item>";
XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
xmlDocFragment.InnerXml = strXml;
xmlDoc.SelectSingleNode("root").AppendChild(xmlDocFragment);
结果:
<root>
<item><name>this is earlier manipulation</name>
<item><name>wrench</name></item>
<item><name>screwdriver</name>
</root>
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
XmlElement root = doc.DocumentElement;
(如果您在谈论XElement,则使用XDocument.Parse:)
XDocument doc = XDocument.Parse("<item><name>wrench</name></item>");
XElement root = doc.Root;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("YOUR XML STRING");
我用了这段代码,得到了解决方案。
// Sample string in the XML format
String s = "<Result> No Records found !<Result/>";
// Create the instance of XmlDocument
XmlDocument doc = new XmlDocument();
// Loads the XML from the string
doc.LoadXml(s);
// Returns the XMLElement of the loaded XML String
XmlElement xe = doc.DocumentElement;
// Print the xe
Console.out.println("Result :" + xe);
如果有更好/更有效的实现方式,请告诉我们。
谢谢 & 干杯
XmlElement[]
时,你会被迫使用奇怪的方法。 - StingyJack