2012-04-10 12 views
6

Ho una stringa XML come questoConverti xmlString in XmlNode

string stxml="<Status>Success</Status>"; 

Ho anche creaated un documento 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); 

ho bisogno di un output come questo.

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

Come posso ottenere this.if noi utilizzando innerHTML, sarà insert.But voglio inserire stringa XML come xmlnode sé

+0

Vedere questa domanda http://stackoverflow.com/questions/4130341/better-way-to-convert-a-string-to-xmlnode-in-c-sharp –

risposta

16

Un modo molto semplice per ottenere ciò che si sta dopo è quello di utilizzare l'spesso trascurato XmlDocumentFragment classe:

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

proverò questo ... – user922834

1

Utilizzando 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

Ho ricevuto un errore come questo ... Impossibile convertire implicitamente il tipo 'System.Xml.Linq.XDocument' in 'System.Xml.XmlDocument' \t Errore – user922834

+0

non è necessario XmlDocument, hai già l'XDocument e basta chiamare Salva se vuoi salvare l'xml – ionden

1

Si potrebbe invece utilizzare la classe 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 

Se si desidera scrivere il nuovo 012.contenuti in un file:

statusList.Save(@"C:\yourFile.xml", SaveOptions.None); 
+0

Anche l'output dovrebbe essere un xml – user922834

+0

yes output shoule be un xml.Come sto chiedendo come inserirlo come nodo .. – user922834

0

si ca provarlo usando XmlWriter

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

     [email protected]"<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 
} 
+0

Potrebbe essere utile aggiungere un po 'di informazioni esplicative per la tua risposta, piuttosto che un semplice blocco di codice propria. –

0

Dalla mia esperienza è sempre meglio lavorare con ID unici che suggerisco di guardare in quella situazione prima e il n torna su questa pagina e cerca/posiziona il mio codice per provare se non avevi ancora una soluzione per questo. Ho appena finito da parte mia per il mio progetto, ho modificato abit per sembrare più integrato per il tuo progetto. Buona fortuna. Ci scusiamo per il ritardo di risposta ;-)

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