XMLReader 基于属性值读取 XML 文件 [英] XMLReader reading XML file based on attribute value

查看:39
本文介绍了XMLReader 基于属性值读取 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取以下文件,我可以读取属性,但无法进入特定元素(在本例中为 Address)并根据该(Address)元素的属性读取其元素.很快,我需要区分工作地址和家庭地址.我需要用 XMLReader 类来做到这一点.你能帮忙吗?

I am trying to read the following file, I can read the attributes, but I can't go into the specific element (Address in this case) and read its elements based on the attribute of that (Address) element. Shortly I need to distinguish between work and home addresses. I need to do this with XMLReader class. Can you help?

    <Address Label="Work">
       <Name>Name1</Name> 
       <Street>PO 1</Street> 
       <City>City1</City> 
       <State>State 1</State> 
    </Address>
    <Address Label="Home">
       <Name>Name2</Name> 
       <Street>PO 2</Street> 
       <City>City2</City> 
       <State>State 2</State>  
    </Address>"

推荐答案

好的,这里有一些注意事项.XMLReader 在我理解你使用它的意义上(没有代码示例)是你迭代文档,因为 XMLReader 是前向的,并且是只读的.

Okay, here are some notes to think about. XMLReader in the sense i understand you use it (with no code example) is that you iterate over the document, since the XMLReader is forward-only, and read-only.

因此,您需要迭代,直到找到所需的节点.在下面的示例中,我找到了标记为work"的地址元素并提取了整个节点.然后根据需要在此节点上查询.

Because of this you need to iterate until you find the node you need. In the example below i find the address element labeled "work" and extract that entire node. Then query on this node as you want.

using (var inFile = new FileStream(path, FileMode.Open))
{
    using (var reader = new XmlTextReader(inFile))
    {
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    if (reader.Name == "Address" && reader.GetAttribute(0) == "Work")
                    {
                        // Create a document, which will contain the address element as the root
                        var doc = new XmlDocument();
                        // Create a reader, which only will read the substree <Address> ... until ... </Address>
                        doc.Load(reader.ReadSubtree());
                        // Use XPath to query the nodes, here the "Name" node
                        var name = doc.SelectSingleNode("//Address/Name");
                        // Print node name and the inner text of the node
                        Console.WriteLine("Node: {0}, Inner text: {1}", name.Name, name.InnerText);
                    }
                    break;
            }
        }
    }
}

编辑

做了一个不使用LINQ的例子

Made an example that not uses LINQ

这篇关于XMLReader 基于属性值读取 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆