从Xml获取值属于Parent

时间:2018-05-28 09:14:03

标签: c# xml

我对阅读,解析xml文件有疑问。 案例:程序读取XML,从OpenFileDialog中选择。这工作正常, 程序读取所有节点。但我的问题在于:我有ID(145,175) - 作为父节点,在它们下面都是四个事务,但是程序循环遍历整个xml并将所有8个事务放在两者之下:

我的代码(摘要):

Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "path_of_my_File";
openFileDialog1.Filter = "xml files (*.xml)|*.xml";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;


if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)
        {
            string path = openFileDialog1.FileName;
            XmlReader xmlFile;
            xmlFile = XmlReader.Create(path, new XmlReaderSettings());
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFile);
            int i = 0;
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("Date", typeof(string));
            dt.Columns.Add("Transaction", typeof(string));
            dt.Columns.Add("Value1", typeof(string));
            dt.Columns.Add("Value2", typeof(string));
            dt.Columns.Add("Value3", typeof(string));
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(path);
            XmlNodeList nodeList = xmldoc.SelectNodes("/statement/retailers/retailer");

            foreach (XmlNode node in nodeList)
            {
                XmlNodeList nodeList2 = xmldoc.SelectNodes("/statement/retailers/retailer/terminals/terminal/transactions");
                DataRow dtrow = dt.NewRow();
                dtrow["ID"] = node.Attributes["ID"].Value;
                dt.Rows.Add(dtrow);

                foreach (XmlNode node2 in nodeList2)
                {
                    dtrow = dt.NewRow();

                    dtrow["Date"] = node2["transaction"].Attributes["date"].Value;
                    dtrow["Transaction"] = node2["transaction"].Attributes["transaction"].Value;
                    dtrow["Value1"] = node2["transaction"].Attributes["Value1"].Value;
                    dtrow["Value2"] = node2["transaction"].Attributes["Value2"].Value;
                    dtrow["Value3"] = node2["transaction"].Attributes["Value3"].Value;
                    dt.Rows.Add(dtrow);
                }
            }

            dataGridView2.DataSource = dt;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

我该怎么说:只把交易属于父母(145个以下的4个交易,175个以下的4个交易?)

结构的虚拟XML:

<root>
<factory name ="145">
    <id name = "xxx" value1 ="b" value2 ="b" value3 ="b" >
</factory>
<factory name ="175">
    <id name = "xxxxxxxxxxxx" value1 ="c" value2 ="c" value3 ="c" >
</factory>
</root>

1 个答案:

答案 0 :(得分:1)

在第二个SelectNodes上,您将在整个文档而不是选定的子节点上应用相应的XPath表达式。要从子节点中进行选择,请使用:

XmlNodeList nodeList2 = node.SelectNodes("./terminals/terminal/transactions");