What is the best way to create an XML document in .NET?

There seem to be many options for creating an XML document in .NET. What is the best approach?

+3
source share
13 answers

XmlWriter has a nice interface for creating a document in a streaming, direct style. It works best if you have a recursive structure that needs to be mapped to XML.

I would use only the DOM API as a last resort. As John says, LINQ to XML is another way. However, no matter what you do, do not go back to formatting strings, as there are subtleties such as namespaces, quoting entities, quoting attributes, etc., which you will need to do correctly.

+4
source

XML ( ), - XmlWriter ( , , , , ):

// Create an XmlWriterSettings object with the correct options.
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = ("\t");
settings.OmitXmlDeclaration = true;

// Create the XmlWriter object and write some content.
using (var writer = XmlWriter.Create("data.xml", settings))
{
    writer.WriteStartElement("book");
    writer.WriteElementString("item", "tesing");
    writer.WriteEndElement();
    writer.Flush();
}

, XmlSerializer, , , , - XmlWriter .

+5

LINQ to XML, . , DOM API. , , .NET 3.5...

, String.Format , , . , - , & < .., .

+4

Xml Serialization: , () , , , , : [XmlElement()], [XmlAttribute()],... XmlSerializer :

public class Car
{
  public string Make;
  public string Model;
}


public class Cars
{
  [XmlElement("Car")]
  public Car[] cars;
}


class Program
{
  public static void Save(Cars cars, string sFilename)
  {
    try
    {
      XmlSerializer ser = new XmlSerializer(cars.GetType());
      FileStream fs = new FileStream(sFilename, FileMode.Create);
      ser.Serialize(fs, cars);
      fs.Close();
    }
    catch (Exception ex)
    { // Failed to save data to disk.
      Debug.WriteLine(string.Format("Failed to save contents of {0}: {1}", sFilename ,ex.Message));
    }
  }
}
+4

PasteXmlAsLinq Visual Studio 2008. C:\Program Files\Microsoft Visual Studio 9.0\Samples\1033\CSharpSamples.zip LinqSamples\PasteXmlAsLinq. Readme , .

+2
+1

string.format( ), , , , , , , , DOM.

DOM.

0

XML- XML

0

, XML, xsd , XML .

0

, , , xml. , - , , , . . . Fluent Interface, api .

        List<string> hierarchyList = new List<string>();
        hierarchyList.Add("Book");
        hierarchyList.Add("Product");
        ConfigurationManager manager = new ConfigurationManager();
        manager.FileName = "deleteme.xml";

        expression = new ConfigurationManagerExpression(manager);
        expression.AddNode("HierarchySet");

        // ROOT_NODE_CONSTANT is the root node of document
        string nodePath = manager.ROOT_NODE_CONSTANT + "/HierarchySet";

        foreach (string name in hierarchyList)
        {
            expression.UsingNode(nodePath).AddNode("HierarchyName").AssignValue(name);
        }

        string panelPrefix = "PE";
        string pathWithFileName = "define your path here";
        manager.SaveSettings(pathWithFileName );
Let me know if you need code and I"ll post it on my blog (which I need to do eventually).
0

XML- MVP.XML.

0
source

Use the API only with a variety of CreateElement, AppendChild, etc. methods.

XmlNode carNode = xmlDocument.CreateElement("Car");
xmlDocument.DocumentElement.AppendChild(carNode);
XmlNode makeNode = xmlDocument.CreateElement("Make");
carNode.AppendChild(makeNode);
...
0
source

Use a string for each component of the document. The values ​​for the document are inserted by String.Format, then LoadXml converts this to an XmlDocument:

string carString =
  "<Car>" +
  "  <Make>{0}</Make>" +
  "  <Model>{1}</Model>" +
  "</Car>";
XmlDocument carDoc = new XmlDocument();
carDoc.LoadXml(String.Format(carString, make, model));
0
source

All Articles