C#xmlserialization SoapEnvelope命名空间格式化

时间:2017-06-04 02:47:38

标签: c# xml serialization soap

我在c#中构建一个soapenvelope时遇到了问题。以下是输出中所需字段的示例

<xml version="1.0">
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
<Body d2p1:type="Body" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
<test xmlns:q1="http://www.w3.org/2001/XMLSchema" d2p1:type="q1:string">hello
</test>
</Body>
</Envelope>

然而,当我序列化课程时,我得到了这个

<xml version="1.0">
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
<test href="#id2" />
</Envelope>
<Body id="id2" d2p1:type="Body" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
<test xmlns:q1="http://www.w3.org/2001/XMLSchema" d2p1:type="q1:string">hello
</test>
</Body>

你可以看到身体在信封之外。

这是班级     命名空间soaptest     {

public class Envelope
{
    public Body test;
}


public class Body
{
    public string test;
}

}

以下是我如何序列化

Envelope test = new Envelope();
MemoryStream ms = new MemoryStream();

test.test = new soaptest.Body();
test.test.test = "hello";

XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);

SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(Envelope));
XmlSerializer serializer = new XmlSerializer(map);
writer.WriteStartElement("xml version=\"1.0\"");
serializer.Serialize(writer, test);

ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string output = sr.ReadToEnd();

现在我可以取消所有属性atm。我只是需要它

 <?xml version="1.0"?>
 <Envelope>
 <Body>
 //body elements
 </Body>
 </Envelope>

那么如何才能让序列化程序执行此操作?或者.net有一个很好的SoapEnvelope库吗?

1 个答案:

答案 0 :(得分:0)

为什么这么复杂?

型号:

public class Envelope
{
    public Body Body;
}
public class Body
{
    [XmlElement("test")]
    public string Test;
}

用法:

Envelope envelope = new Envelope();
envelope.Body = new Body();
envelope.Body.Test = "hello";

XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
serializer.Serialize(Console.Out, envelope);

结果:

<?xml version="1.0" encoding="cp866"?>
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Body>
    <test>hello</test>
  </Body>
</Envelope>