XmlWriter 运行 时间异常

XmlWriter Run Time Exception

当我使用 XmlWriter 写入 XML 文件时,我遇到了以下问题:

我需要写什么:

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

我试过使用XmlWriter.WriteStartElement方法

 XmlWriter.WriteStartElement("soap:Body")  

,但我会得到像 "Invalid name character in 'soap:Body'. The ':' character, hexadecimal value 0x3A, cannot be included in a name."

这样的运行时异常

我是 xmlwriter 的新手,我不知道重载命名空间

如果你知道它建议方法?

您首先必须声明该命名空间 (soap),然后您可以将其与 WriteStartElement 一起使用。

示例:

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();

结果将是:

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

如果要在根元素中使用前缀,可以这样使用:

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();

结果:

<?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>