将xml字符串转换为XmlNode。

7
我有一个XML字符串,如下所示:
string stxml="<Status>Success</Status>";

我也创建了一个XML文档。
  XmlDocument doc = new XmlDocument();
  XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
  doc.AppendChild(docNode);
  XmlNode rootNode = doc.CreateElement("StatusList");
  doc.AppendChild(rootNode);

我需要像这样的输出。
  <StatusList>
  <Status>Success</Status>
  </StatusList>

我该如何实现这个功能呢?如果我们使用innerHTML,它会被插入为文本。但我想要将XML字符串作为XML节点本身插入。

请参考此问题:https://dev59.com/j2855IYBdhLWcg3w0H13 - Ranhiru Jude Cooray
6个回答

18

实现你所需的非常简单的方法是使用经常被忽视的XmlDocumentFragment类:

  XmlDocument doc = new XmlDocument();
  XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
  doc.AppendChild(docNode);
  XmlNode rootNode = doc.CreateElement("StatusList");
  doc.AppendChild(rootNode);

  //Create a document fragment and load the xml into it
  XmlDocumentFragment fragment = doc.CreateDocumentFragment();
  fragment.InnerXml = stxml;
  rootNode.AppendChild(fragment);

1

使用 Linq to XML:

string stxml = "<Status>Success</Status>";
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
             new XElement("StatusList", XElement.Parse(stxml)));

1
我遇到了这样的错误...无法隐式将类型“System.Xml.Linq.XDocument”转换为“System.Xml.XmlDocument”错误。 - user922834
你不需要XmlDocument,因为你已经有了XDocument,如果想要保存xml,只需调用Save即可。 - ionden

1
你可以使用 XElement 类代替:
string stxml = "<Status>Success</Status>";
var status = XElement.Parse(stxml);
var statusList = new XElement("StatusList", status);

var output = statusList.ToString(); // looks as you'd like

如果您想将新的statusList内容写入文件:
statusList.Save(@"C:\yourFile.xml", SaveOptions.None);

0

你可以尝试使用XmlWriter

using (XmlWriter writer = XmlWriter.Create("new.xml"))
{
        writer.WriteStartDocument();
        writer.WriteStartElement("StatusList");
        writer.WriteElementString("Status", "Success");   // <-- These are new
        writer.WriteEndDocument();
}

0
从我的经验来看,最好使用唯一的ID进行工作,我建议您首先查看该情况,然后再回到这个页面,并尝试研究/定位我的代码,如果您还没有解决方案。 我刚刚在自己的项目中完成了它,我已经修改了一些内容,使其更加适合您的项目。 祝你好运。抱歉回复晚了;-)
                XmlDocument xDoc = new XmlDocument();
                string Bingo = "Identification code";
                xDoc.Load(pathFile);
                XmlNodeList idList = xDoc.GetElementsByTagName("id");
                XmlNodeList statusList = xDoc.GetElementsByTagName("Status");         

                for (int i = 0; i < idList.Count; i++)
                {
                    StatusNode = "<Status>fail</Status>";
                    XmlDocumentFragment fragment = xDoc.CreateDocumentFragment();
                    fragment.InnerXml = StatusNode;
                    statusList[i].InnerXml = "";
                    statusList[i].AppendChild(fragment);
                    if (statusList[i].InnerText == Bingo)
                    {
                    StatusNode = "<Status>Succes!</Status>";
                    fragment.InnerXml = Status;
                    statusList[i].InnerXml = "";
                    statusList[i].AppendChild(fragment);


                    }


                }
                xDoc.Save(pathFile);

0
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.ComponentModel;


public class MyClass
{
    public static void RunSnippet()
    {
        XmlNode node = default(XmlNode);
        if(node == null)
            Console.WriteLine(bool.TrueString);
        if(node != null)
            Console.WriteLine(bool.FalseString);

        XmlDocument doc = new  XmlDocument();

        node = doc.CreateNode (XmlNodeType.Element,"Query", string.Empty);

        node.InnerXml=@"<Where><Eq><FieldRef Name=""{0}"" /><Value Type=""{1}"">{2}</Value></Eq></Where>";

        string xmlData = ToXml<XmlNode>(node);

        Console.WriteLine(xmlData);

        XmlNode node1 = ConvertFromString(typeof(XmlNode), @"<Query><Where><Eq><FieldRef Name=""{0}"" /><Value Type=""{1}"">{2}</Value></Eq></Where></Query>") as XmlNode;
        if(node1 == null)
            Console.WriteLine(bool.FalseString);
        if(node1 != null)
            Console.WriteLine(bool.TrueString);

        string xmlData1 = ToXml<XmlNode>(node1);
        Console.WriteLine(xmlData1);
    }
    public static string ToXml<T>(T t)
    {
        string Ret = string.Empty;
        XmlSerializer s = new XmlSerializer(typeof(T));
        using (StringWriter Output = new StringWriter(new System.Text.StringBuilder()))
        {
            s.Serialize(Output, t);
            Ret = Output.ToString();
        }
        return Ret;
    }
        public static object ConvertFromString(Type t, string sourceValue)
        {
            object convertedVal = null;

            Type parameterType = t;
            if (parameterType == null) parameterType = typeof(string);
            try
            {

                // Type t = Type.GetType(sourceType, true);
                TypeConverter converter = TypeDescriptor.GetConverter(parameterType);
                if (converter != null && converter.CanConvertFrom(typeof(string)))
                {
                    convertedVal = converter.ConvertFromString(sourceValue);
                }
                else
                {
                    convertedVal = FromXml(sourceValue, parameterType);
                }
            }
            catch { }
            return convertedVal;
        }
              public static object FromXml(string Xml, Type t)
        {
            object obj;
            XmlSerializer ser = new XmlSerializer(t);
            using (StringReader stringReader = new StringReader(Xml))
            {
                using (System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stringReader))
                {
                    obj = ser.Deserialize(xmlReader);
                }
            }
            return obj;
        }

    #region Helper methods

    public static void Main()
    {
        try
        {
            RunSnippet();
        }
        catch (Exception e)
        {
            string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
            Console.WriteLine(error);
        }
        finally
        {
            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
    }

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

可能添加一些解释性信息到你的回答中会更有用,而不仅仅是一段代码块。 - Neil Mountford

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接