I have an XML file that I need to create in code using XmlWriter. Is there any code generator that will take the XML and generate the lines of c# code to recreate it using XmlWriter?
I took Anurag's response, modified it, and here is what is working for me:
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
using System;
using System.Text;
using System.Xml;
namespace AutoGenerateXmlWriteCode
{
public class TestClass
{
#region Methods
public static void WriteXml()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
settings.OmitXmlDeclaration = true;
using( var writer = XmlWriter.Create("out.xml", settings))
{
<#
foreach (XmlReader node in this.GetNames())
{
if(node.NodeType == XmlNodeType.Element) {
#>
writer.WriteStartElement(@"<#= node.Name #>"); // <#= node.Name #>
<#
if (node.HasAttributes)
{
node.MoveToFirstAttribute();
#>
writer.WriteAttributeString(@"<#= node.Name #>", @"<#= node.Value #>");
<#
while (node.MoveToNextAttribute())
{
#>
writer.WriteAttributeString(@"<#= node.Name #>", @"<#= node.Value #>");
<#
}
node.MoveToElement();
}
if (node.IsEmptyElement){
#>
writer.WriteEndElement(); // <#= node.Name #>
<#
}
}
if(node.NodeType == XmlNodeType.Text) {
#>
writer.WriteValue(@"<#= node.Value #>");
<# }
if(node.NodeType == XmlNodeType.EndElement) {
#>
writer.WriteEndElement(); // <#= node.Name #>
<# }
}
#>
}
}
#endregion
}
}
<#+
public IEnumerable<XmlReader> GetNames()
{
List<string> result = new List<string>();
string absolutePath = @"d:\MyFile.xml";
XmlReader rdr = XmlReader.Create(absolutePath);
while (rdr.Read())
{
yield return rdr;
}
}
#>
You can write your own T4 Template
Here is some code to get you started:
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<# assembly name="System.Xml" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
using System;
using System.Text;
using System.Xml;
namespace Test
{
public class TestClass
{
#region Methods
public static void WriteXml()
{
using( var writer = XmlWriter.Create("out.xml"))
{
<#
foreach (XmlNode node in this.GetNames())
{
if(node.NodeType == XmlNodeType.Element) {
#>
writer.WriteStartElement(@"<#= node.Name #>");
<# }
if(node.NodeType == XmlNodeType.Comment) {
#>
writer.WriteComment(@"<#= node.Value #>");
<# }
}
#>
}
}
#endregion
}
}
<#+
public IEnumerable<XmlNode> GetNames()
{
List<string> result = new List<string>();
XmlDocument doc = new XmlDocument();
string absolutePath = @"c:\data\XMLFile1.xml";
doc.Load(absolutePath);
foreach (XmlNode node in doc.ChildNodes)
{
yield return node;
}
}
#>
Visual studio's Xsd.exe may help you