链接xml文档

时间:2012-12-07 18:44:30

标签: xml

我是xml,xquery和xpath的初学者。是否可以根据它们之间定义的关系将两个单独的xml文档链接在一起?例如,如果我有一个xml文档,其中包含在线零售系统的所有客户,那么(缩短示例):

<customers>
<customer loyaltyPoints = "20" sex = "male">
    <customerID>1092</customerID>
    <first_name>James</first_name>
    <second_name>Roland</second_name>
    <email_address>jroland@eircom.net</email_address>
    <DOB>
        <day>07</day>
        <month>05</month>
        <year>1970</year>    
    </DOB>
    <orderlist>
        <order>[LINK TO ORDER FROM ORDERS.XML]</order>
    </orderlist>
</customer>

和第二个包含一系列订单的xml文件:

<orders>
<order numberOfItems = "2">
    <orderID>384523</orderID>
    <items>
        <item>[LINK TO PRODUCT X IN PRODUCTS.XML]</item>
        <item>[LINK TO PRODUCT Y IN PRODUCTS.XML]</item>
    </items>
</order>
</orders>

我可以将客户链接到其他文档中的订单,反之亦然?非常感谢

1 个答案:

答案 0 :(得分:2)

如果您使用ID作为链接键,则可以执行以下操作:

XmlDocument customerDoc = new XmlDocument();
customerDoc.LoadXml("<customers>
                         <customer loyaltyPoints = \"20\" sex = \"male\">
                         <customerID>1092</customerID>
                         <first_name>James</first_name>
                         <second_name>Roland</second_name>
                         <email_address>jroland@eircom.net</email_address>
                         <DOB>
                             <day>07</day>
                             <month>05</month>
                             <year>1970</year>
                         </DOB>
                         <orderlist>
                             <order>384523</order>
                         </orderlist>
                       </customer>
                    </customers>");

XmlDocument ordersDoc = new XmlDocument();
ordersDoc.LoadXml("<orders>
                       <order numberOfItems = \"2\">
                           <orderID>384523</orderID>
                           <items>
                               <item>[LINK TO PRODUCT X IN PRODUCTS.XML]</item>
                               <item>[LINK TO PRODUCT Y IN PRODUCTS.XML]</item>
                           </items>
                        </order>
                   </orders>");

// Select all "customer" nodes
XmlNodeList nodes = customerDoc.SelectNodes("customers/customer");

foreach (XmlNode node in nodes)
{
     XmlNodeList orderList = node.SelectNodes("orderlist");
     foreach (XmlNode orderNode in orderList)
     {
           string orderId = orderNode.InnerText;
           XmlNode orderInOrderDocNode = ordersDoc.SelectSingleNode("orders/order[orderID='" + orderId + "']");
           Console.WriteLine(orderInOrderDocNode.InnerText);
            }
        }

这将打印出订单节点,该节点在给定客户文档中的orderId的orders.xml文档中找到。

希望这就是你要找的东西。