如何在两个XML标记之间放置一个值,并使用XmlDictionaryWriter为XML元素的名称添加前缀?

时间:2014-03-17 15:04:05

标签: c# xml-serialization

我正在尝试生成以下XML:

<wsse:Security>
  <wsse:BinarySecurityToken
  ValueType="Bibble"
  EncodingType="wsse:Base64Binary"
  wsu:Id="SecurityToken ">
    Fish
  </wsse:BinarySecurityToken>
</wsse:Security>

我的代码是:

protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
    writer.WriteStartElement("wsse", "Security" ,Namespace);
    writer.WriteXmlnsAttribute("wsse", Namespace);
}

protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
    writer.WriteStartElement("wsse", "BinarySecurityToken", Namespace);
    writer.WriteAttributeString("ValueType", "Bibble");
    writer.WriteAttributeString("EncodingType", "wsse:Base64Binary");
    writer.WriteEndElement();
}

问题1:我无法弄清楚如何将Fish的值放在开始和结束标记之间。

问题2:我无法弄清楚如何获取wsu:Id元素,因为此代码会生成异常:writer.WriteAttributeString("wsu:Id", "SecurityToken");

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

  

问题1:

我似乎无法找到XmlDictionaryWriter,但我相信你需要 writer.WriteValue("Fish");

  

问题2:

利用其他一个重载:

writer.WriteAttributeString("wsu", "Id", wsu_namespace_string, "SecurityToken");

其中wsu_namespace_string包含WSU前缀的名称空间声明

答案 1 :(得分:2)

OnWriteHeaderContents()中,在致电writer.WriteEndElement();之前,请添加以下内容:

writer.WriteValue("Fish");

MSDNWriteValue将获取一个字符串并简单地将其写出来。许多不同的CLR类型和object还有其他重载。

所以,OnWriteHeaderContents()看起来像这样:

protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
    writer.WriteStartElement("wsse", "BinarySecurityToken", Namespace);
    writer.WriteAttributeString("ValueType", "Bibble");
    writer.WriteAttributeString("EncodingType", "wsse:Base64Binary");
    writer.WriteValue("Fish");//write Fish
    writer.WriteEndElement();
}