代码之家  ›  专栏  ›  技术社区  ›  Dean

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

  •  55
  • Dean  · 技术社区  · 14 年前

    XmlElement

    你怎么能把它变成 ?

    <item><name>wrench</name></item>
    
    5 回复  |  直到 12 年前
        1
  •  102
  •   Helgi    11 年前

    使用此选项:

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

    如果需要先将此元素添加到另一个文档中,则需要使用 ImportNode

        2
  •  25
  •   johnrock    11 年前

    假设您已经有了一个包含子节点的XmlDocument,并且需要从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);
    

    结果是:

    <root>
      <item><name>this is earlier manipulation</name>
      <item><name>wrench</name></item>
      <item><name>screwdriver</name>
    </root>
    
        3
  •  15
  •   dtb    14 年前

    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;
    
        4
  •  2
  •   Florian    14 年前

    你可以用XmlDocument.LoadXml文件()这样做。

    下面是一个简单的例子:

    XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.LoadXml("YOUR XML STRING"); 
    
        5
  •  0
  •   Nandagopal T    12 年前

    我试过这个片段,找到了解决办法。

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