I need to convert an XML string into an XmlElement

后端 未结 5 810
一个人的身影
一个人的身影 2020-12-14 00:05

I\'m looking for the simplest way to convert a string containing valid XML into an XmlElement object in C#.

How can you turn this into an XmlEleme

相关标签:
5条回答
  • 2020-12-14 00:10

    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 讨论(0)
  • 2020-12-14 00:18

    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;
    
    0 讨论(0)
  • 2020-12-14 00:18

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

    Here is a simple examle:

    XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.LoadXml("YOUR XML STRING"); 
    
    0 讨论(0)
  • 2020-12-14 00:20

    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.

    0 讨论(0)
  • 2020-12-14 00:22

    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>
    
    0 讨论(0)
提交回复
热议问题