XML节点消失



我需要得到2个节点。

<OrderItem>
  +<Product PNR="FFQK2P" Type="Hotel">
  +<Product PNR="SACN8L" Type="Flight">
<OrderItem>

每个Product节点有两个相同的节点。它们是"PriceInfo"one_answers"SearchParameters"。我从;

XmlNode xmlHotelPriceInfo = orderItem.ParentNode.SelectSingleNode("OrderItem/Product/PriceInfo");
XmlNode xmlHotelSearchParametes = orderItem.ParentNode.SelectSingleNode("OrderItem/Product/SearchParameters");

附加节点;

xmlHotel.AppendChild(xmlHotelPriceInfo);
xmlHotel.AppendChild(xmlProductItemInfo);
xmlHotel.AppendChild(xmlHotelSearchParametes);
orderItem.AppendChild(xmlHotel);

该代码完美地创建了节点。在第一个产品;

<Product PNR="FFQK2P" Type="Hotel">
    <PriceInfo>
    <ProductItemInfo
    <SearchParameters>
</Product>

代码在for循环中。在第二个循环中;

xmlFlight.AppendChild(xmlFlightPriceInfo);
xmlFlight.AppendChild(xmlProductItemInfo);
xmlFlight.AppendChild(xmlFlightSearchParametes);
orderItem.AppendChild(xmlFlight);

附加第二个乘积。但是它从第一页删除了PriceInfo和SearchParameters。看起来,

<Product PNR="FFQK2P" Type="Hotel">
    +<ProductItemInfo>
</Product>
<Product PNR="SACN8L" Type="Flight">
    +<PriceInfo>
    +<ProductItemInfo>
    +<SearchParameters>
</Product>

但是我需要得到;

<Product PNR="FFQK2P" Type="Hotel">
    +<PriceInfo>
    +<ProductItemInfo>
    +<SearchParameters>
</Product>
<Product PNR="SACN8L" Type="Flight">
    +<PriceInfo>
    +<ProductItemInfo>
    +<SearchParameters>
</Product>

为什么会出现这种情况?

通过AppendChild方法,您只需更改子节点的所有者(父)节点。看一下CloneNode方法。

所以你的代码应该类似于:
xmlHotel.AppendChild(xmlHotelPriceInfo);
xmlHotel.AppendChild(xmlProductItemInfo);
xmlHotel.AppendChild(xmlHotelSearchParametes);
orderItem.AppendChild(xmlHotel);
...
xmlFlight.AppendChild(xmlFlightPriceInfo.CloneNode(true));
xmlFlight.AppendChild(xmlProductItemInfo.CloneNode(true));
xmlFlight.AppendChild(xmlFlightSearchParametes.CloneNode(true));
orderItem.AppendChild(xmlFlight);

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild.aspx

首先你需要CreateElement,然后AppendChild

最新更新