开发者

I need to convert an XML string into an XmlElement

I'm looking for the simplest 开发者_JAVA百科way to convert a string containing valid XML into an XmlElement object in C#.

How can you turn this into an XmlElement?

<item><name>wrench</name></item>


Use this:

private static XmlElement GetElement(string xml)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    return doc.DocumentElement;
}

Beware!! If you need to add this element to another document first you need to Import it using ImportNode.


Suppose you already had a XmlDocument with children nodes, And you need add more child element from string.

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);

The Result:

<root>
  <item><name>this is earlier manipulation</name>
  <item><name>wrench</name></item>
  <item><name>screwdriver</name>
</root>


Use XmlDocument.LoadXml:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
XmlElement root = doc.DocumentElement;

(Or in case you're talking about XElement, use XDocument.Parse:)

XDocument doc = XDocument.Parse("<item><name>wrench</name></item>");
XElement root = doc.Root;


You can use XmlDocument.LoadXml() to do this.

Here is a simple examle:

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml("YOUR XML STRING"); 


I tried with this snippet, Got the solution.

// 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);

If any other better/ efficient way to implement the same, please let us know.

Thanks & Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜