我需要将XML字符串转换为XmlElement

我正在寻找最简单的方法将包含有效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
将其导入。     
假设您已经有一个带有子节点的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.LoadXml:
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.LoadXml()来执行此操作。 这是一个简单的考试:
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);
如果有任何其他更好/更有效的方法来实现相同的,请告诉我们。 谢谢&amp;干杯     

要回复问题请先登录注册