【问题标题】:C# xmlserialization SoapEnvelope namespace formatingC# xml 序列化 Soap Envelope 命名空间格式化
【发布时间】:2017-06-04 02:47:37
【问题描述】:

我在 C# 中构建肥皂信封时遇到问题。这是输出中所需字段的示例

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

【问题讨论】:

    标签: c# xml serialization soap


    【解决方案1】:

    为什么这么复杂?

    型号:

    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>
    

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      相关资源
      最近更新 更多