CSharpFeeds - All your C# feeds in one place.

Sponsors

Tuesday, September 19, 2006

Improve XML Manipulations with XmlWriter, XmlReader and XPathDocument

by Keyvan Nayyeri via Keyvan Nayyeri on 9/19/2006 7:27:49 PM

Alexey had two informative comments (1, 2) for one of my recent posts about using StringWriter and XmlTextWriter to generate XML files on fly.  He had pointed me to an article on MSDN about some better alternatives for objects I had used in my code in .NET 2.0.

He recommended me to use XmlWriter, XmlReader and XPathDocument instead of XmlTextWriter and XmlDocument.  Before stepping in details I should send my thanksgivings to him (if he hadn't sent these comments, I was coding with that old bad addiction in .NET 2.0).  He also has had a few feedbacks on some of my posts but I can't read them because couldn't find any online translator.

By those replacements, initially I could update my old class as what you'll see.  I just replaced XmlTextWriter with XmlWriter and set it to what XmlWriter.Create() method provides:

public class MyClass

{

    public static string GetXml(bool addId, int id)

    {          

        StringWriter stringWriter =

            new StringWriter();

 

        XmlWriter xmlWriter =

            XmlWriter.Create(stringWriter);

 

        // Start document

        xmlWriter.WriteStartDocument();

 

        xmlWriter.WriteStartElement("myxml");

        if (addId)

            xmlWriter.WriteAttributeString

                ("id", id.ToString());

 

        xmlWriter.WriteAttributeString

            ("attribute1", "value1");

        xmlWriter.WriteAttributeString

            ("attribute2", "value2");

 

        xmlWriter.WriteStartElement

            ("myelement");

        xmlWriter.WriteAttributeString

            ("attribute3", "value3");

 

 

        xmlWriter.WriteElementString

            ("subelement", "This is a value!");

 

        xmlWriter.WriteEndElement();  

 

        // End document

        xmlWriter.WriteEndElement();

 

        xmlWriter.Flush();

        xmlWriter.Close();

        stringWriter.Flush();

 

        return stringWriter.ToString();

    }       

}

After this, I came back to my code to manipulate the XML file that GetXml() method returns and tried to do same thing but this time with XmlReader and XPathDocument:

static void Main(string[] args)

{

    Console.Title = "Create XML File on Fly";

 

    string strXml = MyClass.GetXml(true, 5);          

 

    XmlReader reader = XmlReader.Create

        (new MemoryStream(UTF8Encoding.Default.GetBytes(strXml)));

 

    XPathDocument xpathDoc = new XPathDocument(reader);

 

    XPathNavigator navigator = xpathDoc.CreateNavigator();

    foreach (XPathItem item in

        navigator.Select("/myxml/myelement/subelement"))

    {

        Console.WriteLine(item.Value);

    }

 

    Console.ReadLine();

}

Nothing was wrong with this code but the issue with the UTF-16 encoding that I pointed in my previous post caused an error here:

XmlException

So I tried Robert's solution and wrote my own StringWriterWithEncoding class by inheriting it from StringWriter to accept encoding:

internal class StringWriterWithEncoding : StringWriter

{

    private Encoding myEncoding;

 

    public StringWriterWithEncoding

        (StringBuilder sb, Encoding encoding)

    {

        this.myEncoding = encoding;

    }

 

    public override Encoding Encoding

    { get { return this.myEncoding; } }

}

After creating this class, I modified my first code to use my own StringWriterWithEncoding class:

public class MyClass

{

    public static string GetXml(bool addId, int id)

    {

        StringBuilder sb = new StringBuilder();           

 

        StringWriterWithEncoding stringWriter =

            new StringWriterWithEncoding(sb, Encoding.UTF8);

 

        XmlWriter xmlWriter =

            XmlWriter.Create(stringWriter);

 

        // Start document

        xmlWriter.WriteStartDocument();

 

        xmlWriter.WriteStartElement("myxml");

        if (addId)

            xmlWriter.WriteAttributeString

                ("id", id.ToString());

 

        xmlWriter.WriteAttributeString

            ("attribute1", "value1");

        xmlWriter.WriteAttributeString

            ("attribute2", "value2");

 

        xmlWriter.WriteStartElement

            ("myelement");

        xmlWriter.WriteAttributeString

            ("attribute3", "value3");

 

 

        xmlWriter.WriteElementString

            ("subelement", "This is a value!");

 

        xmlWriter.WriteEndElement();  

 

        // End document

        xmlWriter.WriteEndElement();

 

        xmlWriter.Flush();

        xmlWriter.Close();

        stringWriter.Flush();

 

        return stringWriter.ToString();

    }       

}

And it could solve that error!

email it!bookmark it!digg it!

Original Post: Improve XML Manipulations with XmlWriter, XmlReader and XPathDocument

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us