【问题标题】:Remove all the namespaces from under the root node从根节点下删除所有命名空间
【发布时间】:2017-12-13 16:06:02
【问题描述】:

我正在使用 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片段描述了不同的数据——子元素的命名空间不同。如果你想要底部的:告诉它使用根命名空间

标签: .net xml vb.net serialization namespaces


【解决方案1】:

这里的技巧是,在你想要的xml中,子元素的命名空间是空的命名空间。您的 root 元素在 "http://somewebsite/services/rating" 中,默认情况下命名空间是 inherited;所以:您需要在用于子元素的任何 xml 序列化程序属性中包含 Namespace = ""。例如,如果您有:

[XmlElement("PickupDate")]
public DateTime SomeDate {get;set;}

那么它可能会变成:

[XmlElement("PickupDate", Namespace = "")]
public DateTime SomeDate {get;set;}

您需要对其他元素重复此操作。

【讨论】:

  • 这很完美,也很简单。谢谢!