Lawrance
Lawrance

Reputation: 1055

XmlWriter Run Time Exception

When I use XmlWriter to write XML file, I've encountered a following problem:

what I need to write :

<soap:Body>some xml</soap:Body>

I've tried to use XmlWriter.WriteStartElement method

 XmlWriter.WriteStartElement("soap:Body")  

, but I'll get a runtime exception like "Invalid name character in 'soap:Body'. The ':' character, hexadecimal value 0x3A, cannot be included in a name."

I am new to xmlwriter,I dont know about overloaded with namespace

if u konow about it Suggest way?

Upvotes: 1

Views: 776

Answers (1)

sloth
sloth

Reputation: 101072

You first have to declare that namespace (soap), then you can use it with WriteStartElement.

Example:

writer.WriteStartElement("root");

// Declare a namespace with AttributeString
writer.WriteAttributeString("xmlns", "soap", null, "something:something");

// Use it here
writer.WriteStartElement("Body", "something:something");

writer.WriteString("some xml");
writer.WriteEndElement();
writer.WriteEndElement();

The result will be:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns:soap="something:something">
  <soap:Body>some xml</soap:Body>
</root>

If you want to use a prefix in the root element, you can use something like this:

var soap = "http://www.w3.org/2003/05/soap-envelope";

// use prefix with namespace
writer.WriteStartElement("soap", "Envelope", soap);
writer.WriteStartElement("Body", soap);
writer.WriteString("some xml");
writer.WriteEndElement();
writer.WriteEndElement();

Result:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Body>some xml</soap:Body>
</soap:Envelope>

Upvotes: 2

Related Questions