在c#中使用xmlDocument读取子属性

时间:2012-12-18 11:43:58

标签: c# xml

我想阅读所有order_horder_d属性数据。但是在我的程序代码上只能显示order_h标签data.below是我的代码。感谢

<document>
<order>
<order_h owner="ABC" order_no="96431"/>
    <order_d owner="ABC" order_no="96431" item_no="0153-8196-010">
        <size assoc_id="1274847" size_id="B0153_0150XSXXLNIVINT_VAEC000076_BK"/>
    </order_d>
    <order_d owner="ABC" order_no="96431" item_no="0153-8196-020">
            <size assoc_id="1274847" size_id="B0153_0150XSXXLNIVINT_VAEC000076_BK"/>
    </order_d>
<order_h/>
</order>
<order>
<order_h owner="ABC" order_no="96432">
    <order_d owner="ABC" order_no="96431" item_no="0153-8196-030">
        <size assoc_id="1274847" size_id="B0153_0150XSXXLNIVINT_VAEC000076_BK"/>
    </order_d>
    <order_d owner="ABC" order_no="96431" item_no="0153-8196-040">
            <size assoc_id="1274847" size_id="B0153_0150XSXXLNIVINT_VAEC000076_BK"/>
    </order_d>
<order_h/>
</order>
</document>



 XmlDocument doc = new XmlDocument();
        doc.Load(@"File.xml");

        XmlNode OrderListNode =
 doc.SelectSingleNode("/document");
        XmlNodeList OrderNodeList =
            OrderListNode.SelectNodes("order/order_h");


        foreach (XmlNode node in OrderNodeList)
        {
            Console.WriteLine(node.Attributes.GetNamedItem("owner").Value);
            Console.WriteLine(node.Attributes.GetNamedItem("order_no").Value);
            Console.WriteLine(node.Attributes.GetNamedItem("profoma_po").Value);

            XmlNodeList OrderdNodeList = OrderListNode.SelectNodes("order_h/order_d");
             foreach (XmlNode orderd in OrderdNodeList)
            {
                Console.WriteLine("D " + orderd.Attributes.GetNamedItem("owner").Value);
                Console.WriteLine("D " + orderd.Attributes.GetNamedItem("order_no").Value);
                Console.WriteLine("D " + orderd.Attributes.GetNamedItem("item_no").Value);
            }


            Console.WriteLine("*****************new Line*******************");

        }

1 个答案:

答案 0 :(得分:0)

您需要为另一个对象上的SelectNodes节点调用order_d。如果您希望order_d节点从属于当前node,则需要在SelectNodes上致电node

foreach (XmlNode node in OrderNodeList)
{
    Console.WriteLine(node.Attributes.GetNamedItem("owner").Value);
    Console.WriteLine(node.Attributes.GetNamedItem("order_no").Value);
    Console.WriteLine(node.Attributes.GetNamedItem("profoma_po").Value);

    XmlNodeList OrderdNodeList = node.SelectNodes("/order_d");
    foreach (XmlNode orderd in OrderdNodeList)
    {
        Console.WriteLine("D " + orderd.Attributes.GetNamedItem("owner").Value);
        Console.WriteLine("D " + orderd.Attributes.GetNamedItem("order_no").Value);
        Console.WriteLine("D " + orderd.Attributes.GetNamedItem("item_no").Value);
    }

    Console.WriteLine("*****************new Line*******************");
}