我正在使用system.xml.serialization将类序列化为xdocument。
<tns:RatingRequest xmlns:tns="http://somewebsite/services/rating"
xmlns:tns1="http://somewebsite/services/rating"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://somewebsite/services/rating.xsd ">
<tns:Configuration>
<tns:Client>
<tns:TradingPartnerNum>101010</tns:TradingPartnerNum>
</tns:Client>
</tns:Configuration>
<tns:PickupDate>2017-12-12T00:00:00</tns:PickupDate>
<tns:LatestDeliveryDate>0001-01-01T00:00:00</tns:LatestDeliveryDate>
<tns:Stops>
<tns:Index>1</tns:Index>
</tns:Stops>
</tns:RatingRequest>
我需要的只是一个具有TNS的节点:命名空间
<tns:RatingRequest xmlns:tns="http://somewebsite/services/rating"
xmlns:tns1="http://somewebsite/services/rating"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://somewebsite/services/rating.xsd ">
<Configuration>
<TradingPartner>
<TradingPartnerNum>101010</TradingPartnerNum>
</TradingPartner>
</Configuration>
<PickupDate>2017-10-27T00:00:00-05:00</PickupDate>
<DeliveryDate>-05:00</DeliveryDate>
<Stops>
<Stop>
<Index>1</Index>
</stop>
</stops>
</tns:RatingRequest>
有没有干净的方法?
的诀窍是,在您想要的XML中,子元素的名称空间是空名称空间。您的 root 元素在 "http://somewebsite/services/rating"
中,默认情况下,名称空间为 senasented ;因此:您需要在用于子元素的任何XML Serializer属性上包括Namespace = ""
。例如,如果您有:
[XmlElement("PickupDate")]
public DateTime SomeDate {get;set;}
然后可能会变成:
[XmlElement("PickupDate", Namespace = "")]
public DateTime SomeDate {get;set;}
您需要重复其他元素。