Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an XML Element object from an XML Writer in C#

Tags:

c#

xml

xmlwriter

I'm writing a Windows service in C#. I've got an XmlWriter which is contains the output of an XSLT transformation. I need to get the XML into an XMLElement object to pass to a web service.

What is the best way to do this?

like image 796
macleojw Avatar asked Feb 18 '09 12:02

macleojw


People also ask

How do you create an XmlWriter?

Creates a new XmlWriter instance using the stream and XmlWriterSettings object. Creates a new XmlWriter instance using the specified XmlWriter and XmlWriterSettings objects. Creates a new XmlWriter instance using the specified StringBuilder. Creates a new XmlWriter instance using the specified filename.

What is XML writer?

XmlTextWriter Class (System.Xml) Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

How read and write data from XML in C#?

The XmlReader, XmlWriter and their derived classes contains methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively.

Which method of XML text writer class is used to put value for attribute of XML?

WriteAttributeString("xmlns","x",null,"abc"); By using the write methods that take a prefix as an argument you can also specify which prefix to use. In the following example, two different prefixes are mapped to the same namespace URI to produce the XML text <x:root xmlns:x="urn:1"><y:item xmlns:y="urn:1"/></x:root> .


2 Answers

You do not need an intermediate string, you can create an XmlWriter that writes directly into an XmlNode:

XmlDocument doc = new XmlDocument();
using (XmlWriter xw = doc.CreateNavigator().AppendChild()) {
  // Write to `xw` here.
  // Nodes written to `xw` will not appear in the document 
  // until `xw` is closed/disposed.
}

and pass xw as the output of the transform.

NB. Some parts of the xsl:output will be ignored (e.g. encoding) because the XmlDocument will use its own settings.

like image 105
Richard Avatar answered Sep 22 '22 14:09

Richard


Well, an XmlWriter doesn't contain the output; typically, you have a backing object (maybe a StringBuilder or MemoryStream) that is the dumping place. In this case, StringBuilder is probably the most efficient... perhaps something like:

    StringBuilder sb = new StringBuilder();
    using (XmlWriter writer = XmlWriter.Create(sb))
    {
        // TODO write to writer via xslt
    }
    string xml = sb.ToString();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    XmlElement el = doc.DocumentElement;
like image 30
Marc Gravell Avatar answered Sep 21 '22 14:09

Marc Gravell