5

I have noticed that XmlWriter.WriteRaw appears to not work properly (it escapes xml characters) when the writer is created using XElement.CreateWriter. The below test case reproduces the problem. Is my usage incorrect? Does anyone know how to achieve the desired behavior? I need to be able to write a raw xml string to an XmlWriter and incorporate that xml into an XElement.

[Test]
public void XElementWriterTest()
{
    var xelement = new XElement("test");
    using (var writer = xelement.CreateWriter())
    {
        writer.WriteRaw(@"<some raw='xml' />");
    }
    Assert.That(xelement.ToString(), Is.EqualTo(@"<test><some raw='xml' /></test>"));
    // actual : "<test>&lt;some raw='xml' /&gt;</test>"
}
Stuart Lange
  • 4,049
  • 6
  • 24
  • 30
  • Without getting into the details, I'm trying to retrofit an existing framework that utilizes XmlWriter to use XNode (and friends). I need this functionality as a shim from the new way I'm trying to do things to the old way of doing things that many users of the framework rely on. – Stuart Lange Feb 23 '12 at 18:15
  • Wow - that is strange. And yet it works as you'd expect if you create a writer via `XmlWriter.Create`. What an odd bit of behaviour! – Rob Levine Feb 23 '12 at 18:21
  • WriteRaw allows you to write something out to a file or stream that breaks XML syntax rules. If you use LINQ to XML you are dealing with nodes that represent well-formed XML documents and not some variation of the XML syntax. Furthermore the nodes do not store syntax details like quote characters delimiting attribute values so you won't be able to store such detail with LINQ to XML at all, whether you use WriteRaw or other methods. So your assert with never work as LINQ to XML does not store attribute value delimiters and ToString serializes the node back to a string. – Martin Honnen Feb 23 '12 at 18:25
  • 1
    Good point, @Martin, that makes a lot of sense. I suppose only the "structured" calls to XmlWriter (WriteStartElement, WriteAttributeString, etc) are valid on an XmlWriter created via XElement.CreateWriter(). As Rob pointed out, it is a bit unexpected that an XmlWriter created from an XElement behaves differently than an XmlWriter created explicitly (via XmlWriter.Create). – Stuart Lange Feb 23 '12 at 20:27

1 Answers1

-1

Is XElement.Parse() an option for you at all?

[TestMethod]
public void XElementWriterTest()
{
    var xelement = new XElement("test");
    const string newXML = @"<some raw='xml' />";
    var child = XElement.Parse(newXML);
    xelement.Add(child);
    Assert.AreEqual(xelement.ToString(SaveOptions.DisableFormatting), @"<test><some raw=""xml"" /></test>");
}
jhilden
  • 12,207
  • 5
  • 53
  • 76