2012-04-06 10 views
8

Sto usando XmlWriterSettings per scrivere Xml su file. Ho elementi con solo attributi, senza figli. Io li voglio uscita come:Richiedere XmlWriterSettings per utilizzare i tag a chiusura automatica

<element a="1" /> 

invece di

<element a="1"></element> 

Posso farlo con XmlWriterSettings?

EDIT:

codice è il seguente:

private void Mission_Save(string fileName) 
    { 
     StreamWriter streamWriter = new StreamWriter(fileName, false); 
     streamWriter.Write(Mission_ToXml()); 
     streamWriter.Close(); 
     streamWriter.Dispose(); 

     _MissionFilePath = fileName; 
    } 

private string Mission_ToXml() 
    { 
     XmlDocument xDoc; 
     XmlElement root; 
     XmlAttribute xAtt; 

     xDoc = new XmlDocument(); 

     foreach (string item in _MissionCommentsBefore) 
      xDoc.AppendChild(xDoc.CreateComment(item)); 

     root = xDoc.CreateElement("mission_data"); 
     xAtt = xDoc.CreateAttribute("version"); 
     xAtt.Value = "1.61"; 
     root.Attributes.Append(xAtt); 
     xDoc.AppendChild(root); 

     //Out the xml's! 
     foreach (TreeNode node in _FM_tve_Mission.Nodes) 
      Mission_ToXml_private_RecursivelyOut(root, xDoc, node); 

     foreach (string item in _MissionCommentsAfter) 
      xDoc.AppendChild(xDoc.CreateComment(item)); 


     //Make this look good 
     StringBuilder sb = new StringBuilder(); 
     XmlWriterSettings settings = new XmlWriterSettings(); 

     settings.Indent = true; 
     settings.IndentChars = " "; 
     settings.NewLineChars = "\r\n"; 
     settings.NewLineHandling = NewLineHandling.Replace; 
     settings.OmitXmlDeclaration = true; 
     using (XmlWriter writer = XmlWriter.Create(sb, settings)) 
     { 
      xDoc.Save(writer); 
     } 

     return sb.ToString(); 
    } 

private void Mission_ToXml_private_RecursivelyOut(XmlNode root, XmlDocument xDoc, TreeNode tNode) 
    { 
     root.AppendChild(((MissionNode)tNode.Tag).ToXml(xDoc)); 
     foreach (TreeNode node in tNode.Nodes) 
      Mission_ToXml_private_RecursivelyOut(root, xDoc, node); 
    } 

qui _FM_tve_Mission è un controllo TreeView che ha nodi, ciascuno dei nodi ha un tag di classe MissionNode, che ha il metodo toxml che restituisce XmlNode contenente questo MissionNode convertito in xml

+0

qual è il tuo codice? Un [XmlWriter senza impostazioni specifiche] (http://ideone.com/g158S) li scrive nel modo desiderato –

risposta

8

Non avete bisogno di impostazioni particolari per questo:

XmlWriter output = XmlWriter.Create(filepath); 
output.writeStartElement("element"); 
output.writeAttributeString("a", "1"); 
output.writeEndElement(); 

che vi darà una potenza di <element a="1" /> (appena provato in un'applicazione sto lavorando sulla scrittura xml per)

In sostanza se non aggiungere i dati prima di scrivere l'elemento terminale sarà solo chiuderlo fuori per voi .

devo anche i seguenti XmlWriterSettings può essere uno di questi se si mangia di lavoro di default:

XmlWriterSettings wSettings = new XmlWriterSettings(); 
wSettings.Indent = true; 
wSettings.ConformanceLevel = ConformanceLevel.Fragment; 
wSettings.OmitXmlDeclaration = true; 
XmlWriter output = XmlWriter.Create(filePathXml, wSettings); 
+0

No no no, non lo capisci. Ho un XML molto complesso, in realtà è un editor di missioni per un gioco che memorizza scenari (set di script ed eventi e cose) in formato xml, quindi è generato dinamicamente e mi piacerebbe ust xmlwriter per stamparlo facendo semplicemente XmlWriter. Write (myXml) – Istrebitel

+0

XmlWriter ha solo un metodo 'Create' statico. Non puoi chiamare 'XmlWriter.Write()' perché non esiste. Devi scrivere ogni nodo con il nome e gli attributi individualmente. Dalla spiegazione che hai dato questo è esattamente quello che vuoi. Non puoi semplicemente passare magicamente i dati a xmlwriter e aspettarti l'output. Devi dirgli quali elementi e attributi produrre. – jzworkman

+0

Ah scusa se ho sbagliato, si chiama Save not Write ....Quello che intendevo è usare l'oggetto di tipo XmlDocument's metodo Save (passando l'oggetto XmlWriter), ho aggiunto il codice all'OP – Istrebitel

1

Elaborare XML da un file esterno, ho scritto la seguente classe di sbarazzarsi di non-Vuoto Chiuso Elementi. Il mio XML ora ha tag di chiusura automatica.

using System.Linq; 
using System.Xml.Linq; 

namespace XmlBeautifier 
{ 
    public class XmlBeautifier 
    { 
     public static string BeautifyXml(string outerXml) 
     { 
      var _elementOriginalXml = XElement.Parse(outerXml); 
      var _beautifiedXml = CloneElement(_elementOriginalXml); 
      return _beautifiedXml.ToString(); 
     } 

     public static XElement CloneElement(XElement element) 
     { 
      // http://blogs.msdn.com/b/ericwhite/archive/2009/07/08/empty-elements-and-self-closing-tags.aspx 
      return new XElement(element.Name, 
       element.Attributes(), 
       element.Nodes().Select(n => 
       { 
        XElement e = n as XElement; 
        if (e != null) 
         return CloneElement(e); 
        return n; 
       }) 
      ); 
     } 

    } 
} 
0

Con Regex e metodo ricorsivo, è facile lavoro:

using System.Xml.Linq; 
    public static class Xml 
    { 
     /// <summary> 
     /// Recursive method to shorten all xml end tags starting from a given element, and running through all sub elements 
     /// </summary> 
     /// <param name="elem">Starting point element</param> 
     public static void ToShortEndTags(this XElement elem) 
     { 
      if (elem == null) return; 

      if (elem.HasElements) 
      { 
       foreach (var item in elem.Elements()) ToShortEndTags(item); 
       return; 
      } 

      var reduced = Regex.Replace(elem.ToString(), ">[\\s\\n\\r]*</\\w+>", "/>"); 

      elem.ReplaceWith(XElement.Parse(reduced)); 
     } 
    } 

e di utilizzarlo, tipo qualcosa di simile:

var path = @"C:\SomeFile.xml"; 
    var xdoc = XDocument.Load(path).Root.ToShortEndTags(); 

xdoc è ora, un esempio di XDocument caricato dal percorso specificato, ma tutti i suoi titoli idonei (senza contenuto) sono ora Short ened

Problemi correlati