C# 将xmlstring转换为XmlNode

C# 将xmlstring转换为XmlNode,c#,.net,xml,C#,.net,Xml,我有一个这样的xml字符串 string stxml="<Status>Success</Status>"; 我需要这样的输出 <StatusList> <Status>Success</Status> </StatusList> 成功 如何实现这一点。如果我们使用innerhtml,它将插入。但我想使用Linq to xml将xml字符串作为xmlnode本身插入: string stxml = "&l

我有一个这样的xml字符串

string stxml="<Status>Success</Status>";
我需要这样的输出

  <StatusList>
  <Status>Success</Status>
  </StatusList>

成功

如何实现这一点。如果我们使用innerhtml,它将插入。但我想使用
Linq to xml将xml字符串作为xmlnode本身插入:

string stxml = "<Status>Success</Status>";
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
             new XElement("StatusList", XElement.Parse(stxml)));
string stxml=“Success”;
XDocument doc=新XDocument(新XDeclaration(“1.0”、“utf-8”、“是”),
新的XElement(“StatusList”,XElement.Parse(stxml));
您可以改为使用该类:


您可以使用xmlwriter进行尝试

using (XmlWriter writer = XmlWriter.Create("new.xml"))
{
        writer.WriteStartDocument();
        writer.WriteStartElement("StatusList");
        writer.WriteElementString("Status", "Success");   // <-- These are new
        writer.WriteEndDocument();
}
使用(XmlWriter=XmlWriter.Create(“new.xml”))
{
writer.WriteStartDocument();
writer.writeStarteElement(“状态列表”);

writer.WriteElementString(“Status”,“Success”);//实现您所追求的目标的一个非常简单的方法是使用经常被忽略的类:

使用系统;
使用System.Collections.Generic;
使用System.Xml;
使用System.Xml.Serialization;
使用System.IO;
运用系统反思;
使用系统组件模型;
公共类MyClass
{
公共静态void RunSnippet()
{
XmlNode=default(XmlNode);
if(node==null)
Console.WriteLine(bool.TrueString);
如果(节点!=null)
Console.WriteLine(bool.false字符串);
XmlDocument doc=新的XmlDocument();
node=doc.CreateNode(XmlNodeType.Element,“Query”,string.Empty);
node.InnerXml=@“{2}”;
字符串xmlData=ToXml(节点);
Console.WriteLine(xmlData);
xmlnode1=ConvertFromString(typeof(XmlNode),@“{2}”)作为XmlNode;
if(node1==null)
Console.WriteLine(bool.false字符串);
if(node1!=null)
Console.WriteLine(bool.TrueString);
字符串xmlData1=ToXml(node1);
Console.WriteLine(xmlData1);
}
公共静态字符串ToXml(T)
{
string Ret=string.Empty;
XmlSerializer s=新的XmlSerializer(typeof(T));
使用(StringWriter输出=新的StringWriter(new System.Text.StringBuilder()))
{
s、 序列化(输出,t);
Ret=Output.ToString();
}
返回Ret;
}
公共静态对象ConvertFromString(类型t,字符串源值)
{
对象convertedVal=null;
类型参数Type=t;
如果(parameterType==null)parameterType=typeof(字符串);
尝试
{
//Type t=Type.GetType(sourceType,true);
TypeConverter converter=TypeDescriptor.GetConverter(参数类型);
if(converter!=null&&converter.CanConvertFrom(typeof(string)))
{
convertedVal=converter.ConvertFromString(sourceValue);
}
其他的
{
convertedVal=FromXml(sourceValue,parameterType);
}
}
捕获{}
返回转换值;
}
来自Xml的公共静态对象(字符串Xml,类型t)
{
对象对象对象;
XmlSerializer ser=新的XmlSerializer(t);
使用(StringReader StringReader=new StringReader(Xml))
{
使用(System.Xml.XmlTextReader=new System.Xml.XmlTextReader(stringReader))
{
obj=序列反序列化(xmlReader);
}
}
返回obj;
}
#区域辅助方法
公共静态void Main()
{
尝试
{
RunSnippet();
}
捕获(例外e)
{
string error=string.Format(“--\n执行代码段时发生以下错误:\n{0}\n--”,e.ToString());
控制台写入线(错误);
}
最后
{
控制台。写入(“按任意键继续…”);
Console.ReadKey();
}
}
私有静态void WL(对象文本,参数对象[]args)
{
Console.WriteLine(text.ToString(),args);
}
私有静态void RL()
{
Console.ReadLine();
}
私有静态void Break()
{
System.Diagnostics.Debugger.Break();
}
#端区
}

根据我的经验,使用unique id总是更好。我建议你先看看这种情况,然后再回到本页,如果你还没有解决方案,研究/定位我的代码进行尝试。 我刚刚为我自己的项目完成了它,我修改了abit,使它看起来更适合您的项目。 祝你好运。很抱歉反应太晚;-)

XmlDocument xDoc=new XmlDocument();
字符串Bingo=“识别码”;
加载(路径文件);
XmlNodeList idList=xDoc.GetElementsByTagName(“id”);
XmlNodeList statusList=xDoc.GetElementsByTagName(“状态”);
for(int i=0;i
看到这个问题,我遇到了一个类似这样的错误……无法将类型“System.Xml.Linq.XDocument”隐式转换为“System.Xml.XmlDocument”错误您不需要XmlDocument,您已经有了XDocument,如果您想保存XmlDocument,只需调用Save即可。在答案中添加一些解释性信息,而不仅仅是一个代码块本身。
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.Save(@"C:\yourFile.xml", SaveOptions.None);
using (XmlWriter writer = XmlWriter.Create("new.xml"))
{
        writer.WriteStartDocument();
        writer.WriteStartElement("StatusList");
        writer.WriteElementString("Status", "Success");   // <-- These are new
        writer.WriteEndDocument();
}
  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);
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
}
                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);