views:

93

answers:

2

Hello,

How do I get this output?

<MSRP currency="USD">10.00</MSRP>

writer.WriteElementString("MSRP", Convert.ToString(q.ItemPrice1));

writer.WriteAttributeString("currency", "MSRP", "USD");

this is the error:

Token StartAttribute in state Content would result in an invalid XML document.

+4  A: 
writer.WriteStartElement( "MSRP" );
writer.WriteAttributeString( "currency", "USD" );
writer.WriteString( q.ItemPrice1.ToString() );
writer.WriteEndElement();

When you call WriteElementString it writes the entire element all at once - no chance to later add attributes. You have to open the element with WriteStartElement...then close it with WriteEndElement.

Paul Alexander
I would look into maybe using the XmlConvert class to convert the ItemPrice1 to an Xml compliant string representation of the number (unless you want control over the number of decimal places; "10.00" will be converted to just 10).
Fredrik Mörk
q.ItemPrice1.ToString(); does not work... have to use Convert.ToString(q.ItemPrice1);
Scott Kramer
What is the type of the ItemPrice1 property? The Convert.ToString method just calls ToString for most types.
Paul Alexander
+1  A: 

I believe this will do the trick.

writer.WriteStartElement("MSRP");
writer.WriteAttributeString("currency", "USD");
writer.WriteValue("10.00");
writer.WriteEndElement();

See the documentation at msdn

Kris
what is better, writevalue or writestring?
Scott Kramer
Actually i don't think it'll matter, As long as the compiler knows you're writing a string. WriteValue is just more flexible and sounds closer to DOMElement.NodeValue
Kris