2017-06-04 75 views
0

我在使用c#構建soapenvelope時遇到了問題。下面是所需的字段的輸出C#xmlserialization 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庫?

回答

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>