【问题标题】:Convert xmlstring into XmlNode将 xmlstring 转换为 XmlNode
【发布时间】:2012-04-10 05:30:39
【问题描述】:

我有一个这样的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字符串作为xmlnode本身插入

【问题讨论】:

标签: c# .net xml


【解决方案1】:

实现您所追求的一个非常简单的方法是使用经常被忽视的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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我遇到这样的错误...无法将类型“System.Xml.Linq.XDocument”隐式转换为“System.Xml.XmlDocument”错误
    • 你不需要 XmlDocument,你已经有了 XDocument,如果你想保存 xml,只需调用 Save
    【解决方案3】:

    您可以改用 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);
    

    【讨论】:

      【解决方案4】:

      你可以用 xmlwriter 试试

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

      【讨论】:

        【解决方案5】:
        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
        }
        

        【讨论】:

        • 在您的答案中添加一点解释性信息可能会很有用,而不仅仅是一个代码块。
        【解决方案6】:

        根据我的经验,最好使用唯一 ID . 我刚刚为我自己的项目完成了它,我已经修改了 abit 以使其看起来更适合您的项目。 祝你好运。抱歉回复晚了 ;-)

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

        【讨论】:

          猜你喜欢
          • 2011-07-20
          • 2010-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-27
          • 1970-01-01
          相关资源
          最近更新 更多