简体   繁体   English

XMLReader根据属性值读取XML文件

[英]XMLReader reading XML file based on attribute value

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. 我正在尝试读取以下文件,可以读取属性,但是无法进入特定元素(在这种情况下为Address),并且无法基于该(Address)元素的属性读取其元素。 Shortly I need to distinguish between work and home addresses. 不久,我需要区分工作地址和家庭住址。 I need to do this with XMLReader class. 我需要使用XMLReader类来做到这一点。 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>"

XML: XML:

<Countries>
  <Country name ="ANDORRA">
    <state>Andorra (general)</state>
    <state>Andorra</state>
  </Country>
  <Country name ="United Arab Emirates">
    <state>Abu Z¸aby</state>
    <state>Umm al Qaywayn</state>
  </Country>

Java: Java的:

 public void datass(string file)
  {

            string file = HttpContext.Current.Server.MapPath("~/App_Data/CS.xml");
                XmlDocument doc = new XmlDocument();
                if (System.IO.File.Exists(file))
                {
                    //Load the XML File
                    doc.Load(file);

                }


                //Get the root element
                XmlElement root = doc.DocumentElement;
                XmlNodeList subroot = root.SelectNodes("Country");

                for (int i = 0; i < subroot.Count; i++)     
                {

                    XmlNode elem = subroot.Item(i);
                    string attrVal = elem.Attributes["name"].Value;
                    Response.Write(attrVal);
                    XmlNodeList sub = elem.SelectNodes("state");
                    for (int j = 0; j < sub.Count; j++)
                    {
                        XmlNode elem1 = sub.Item(j);
                        Response.Write(elem1.InnerText);

                    }
                }

    }

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. 我理解您使用XMLReader (没有代码示例)的意义是,您遍历文档,因为XMLReader是仅转发的,并且是只读的。

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;
            }
        }
    }
}

Edit 编辑

Made an example that not uses LINQ 做了一个不使用LINQ的示例

Using XPath you can easily write concise expressions to navigate an XML document. 使用XPath,您可以轻松编写简洁的表达式来浏览XML文档。

You would do something like 你会做类似的事情

XmlDocument xDoc = new XmlDocument();

xDoc.LoadXml(myXMLString);

XmlNode homeAddress = xDoc.SelectSingleNode("//Address[@Label='Work']");

Then do whatever you want with homeAddress . 然后使用homeAddress进行任何homeAddress

Read more here on w3schools on XPath. 在XPath的w3schools上了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM