2

I'm using XmlTextWriter to generate XML from a C# app. The initial input will be in this format, 1" , but I can replace it with whatever. I need to end up with 1" but I keep getting 1"

C#

    xml.WriteStartElement("data");
    xml.WriteAttributeString("type", "wstring");
    xml.WriteString("1"");
    xml.WriteEndElement();

Ha! When I past the XML I need in here it converts it to 1". But whats I really need to show is the actual 1" in the 3rd line of the code.

I also need to use / and Ø. How can I do this, thanks.

code4life
  • 15,655
  • 7
  • 50
  • 82
topofsteel
  • 1,267
  • 6
  • 16
  • 25

1 Answers1

5

I need to end up with 1" but I keep getting 1"

That's because you're trying to do the XML API's job for it.

Your job is to provide just text - its job is to handle escaping and anything else XML needs to do.

So you should just use

xml.WriteString("1\"");

... where the backslash is just for the sake of C#'s string literal handling, and has nothing to do with XML. The logical value you're trying to write out is a 1 followed by a double-quote. Whether it's escaped as " or not should be irrelevant to anything processing it. If you've got something which is over-sensitive, you should fix that.

If you desperately need this (and I would again strongly urge you not to), try:

xml.WriteString("1");
xml.WriteEntityRef("quot");

(I'd also urge you to use LINQ to XML unless you're in a situation where you really need to use XmlWriter. It'll make your life significantly simpler.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • The answer gives me 1", i need to end up with '1"'. The XML is being used as a search. I'm trying to reproduce the output. – topofsteel Dec 07 '12 at 18:52
  • @topofsteel: They're equivalent in XML, other than situations where the escaping is *required* (which it isn't in a text node). Anything processing the XML should treat it th same way. – Jon Skeet Dec 07 '12 at 18:54
  • @topofsteel: See my edit for more details and an alternative, but please consider the alternatives. – Jon Skeet Dec 07 '12 at 18:56