【问题标题】:Parse XML using DOM in android在android中使用DOM解析XML
【发布时间】:2013-01-20 08:00:38
【问题描述】:

您好,我想根据用户的选择解析 XML 并显示列表

我的 xml 看起来像这样

下面是我的代码

      try {
            XMLParser parser = new XMLParser();
            Document doc = parser.getDomElement(xml); // getting DOM element
            NodeList n1 = doc.getElementsByTagName("company");

            // looping through all item nodes <item>
            for (int i = 0; i < n1.getLength(); i++) {
                // creating new HashMap
                Element e = (Element) n1.item(i);

                System.out.println("name node "+parser.getValue(e, "name"));
            }

通过这种方式,我得到了类似的输出

  Company ABC
  Company XYZ

公司列表

但是
我会写像

这样的代码
        NodeList n1 = doc.getElementsByTagName("province"); 
        // looping through all item nodes <item>
            for (int i = 0; i < n1.getLength(); i++) {
                // creating new HashMap
                Element e = (Element) n1.item(i);

                System.out.println("name node "+parser.getValue(e, "name"));
            }

我正在获取省份名称列表

   Alberta
   Ontario
   New York
   Florida

但它应该像这样工作

当我选择公司 ABC 时

应该只显示两个供应列表

       Alberta
       Ontario

不应该所有显示都可以帮助我如何重写我的代码

【问题讨论】:

  • 我应该使用另一种 XML 方法还是使用这种方式!!!

标签: java android xml xml-parsing


【解决方案1】:

应该这样做:

        XMLParser parser = new XMLParser();
        Document doc = parser.getDomElement(xml); // getting DOM element
        NodeList n1 = doc.getElementsByTagName("company");

        // looping through all item nodes <item>
        for (int i = 0; i < n1.getLength(); i++) {
            Element e = (Element) n1.item(i);
            System.out.println("name node "  +parser.getValue(e, "name"));
            NodeList children = e.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                 Node child = children.item(j);
                 if (child.getNodeName().equalsIgnoreCase("province")) {
                      System.out.println("name node " + parser.getValue((Element)child, "name"));
                 }
            }
        }

【讨论】:

  • 子节点=nodes.item(i);什么是节点??是孩子吗?
  • 抱歉打错了,应该是Node child = children.item(j);
  • 是的,我已经完成了,但 parser.getValue(child, "name")) 上仍然出错;
  • XMLParser 类型中的getValue(Element, String) 方法不适用于参数(Node, String)
  • 应该是parser.getValue((Element)child, "name")。对不起,我写了这段代码,从来没有编译过。它应该给你一个想法,像这样的小问题你应该能够自己解决。
【解决方案2】:

在“公司”节点上使用Node.getChildNodes()。然后,要获取子省节点,按名称进行比较。示例:

    XMLParser parser = new XMLParser();
    Document doc = parser.getDomElement(xml); // getting DOM element
    NodeList n1 = doc.getElementsByTagName("company");

    // looping through all item nodes <item>
    for (int i = 0; i < n1.getLength(); i++) {
        Node companyNode = n1.item(i);
        NodeList childNodes = companyNode.getChildNodes();
        // Here we're getting child nodes inside the company node.
        // Only direct childs will be returned (name and province)  

        for (int j = 0; j < childNodes.getLength(); j++) {
            Node childNode = childNodes.item(j);
            if("province".equalsIgnoreCase(childNode.getName())){
                //Do something with province
            }
        }
    }

【讨论】:

  • 你能举例说明一下吗
【解决方案3】:

试试下面的代码:

public class MainActivity  extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /** Create a new layout to display the view */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(1);

    /** Create a new textview array to display the results */
    TextView name[];
    TextView website[];
    TextView category[];

    try {

        URL url = new URL(
                "http://xyz.com/aa.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName("item");

        /** Assign textview array lenght by arraylist size */
        name = new TextView[nodeList.getLength()];
        website = new TextView[nodeList.getLength()];
        category = new TextView[nodeList.getLength()];

        for (int i = 0; i < nodeList.getLength(); i++) {

            Node node = nodeList.item(i);

            name[i] = new TextView(this);
            website[i] = new TextView(this);
            category[i] = new TextView(this);

            Element fstElmnt = (Element) node;
            NodeList nameList = fstElmnt.getElementsByTagName("name");
            Element nameElement = (Element) nameList.item(0);
            nameList = nameElement.getChildNodes();
            name[i].setText("Name = "
                    + ((Node) nameList.item(0)).getNodeValue());

            NodeList websiteList = fstElmnt.getElementsByTagName("website");
            Element websiteElement = (Element) websiteList.item(0);
            websiteList = websiteElement.getChildNodes();
            website[i].setText("Website = "
                    + ((Node) websiteList.item(0)).getNodeValue());

            category[i].setText("Website Category = "
                    + websiteElement.getAttribute("category"));

            layout.addView(name[i]);
            layout.addView(website[i]);
            layout.addView(category[i]);

        }
    } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
    }

    /** Set the layout view to display */
    setContentView(layout);

}
}

【讨论】:

    【解决方案4】:

    在文档对象上调用的 getElementsBytagName 将始终返回整个文档中具有给定标签名称的所有节点的列表。相反,过滤掉您感兴趣的单个公司元素,然后在 it 上调用 getElementsByTagName。例如

    Element companyEl = doc.getElementById(desiredCompanyId);
    if (companyEl != null) { // always good to check
        NodeList n1 = companyEl.getElementsByTagName("province");
    
        // your code here
    }
    

    【讨论】:

      【解决方案5】:

      试试这段代码

      for (int i = 0; i

              Node node = nodeList.item(i);
      
              name[i] = new TextView(this);
              website[i] = new TextView(this);
              category[i] = new TextView(this);
      
              Element fstElmnt = (Element) node;
              NodeList nameList = fstElmnt.getElementsByTagName("name");
              Element nameElement = (Element) nameList.item(0);
              nameList = nameElement.getChildNodes();
              name[i].setText("Name = "
                      + ((Node) nameList.item(0)).getNodeValue());
      
              NodeList websiteList = fstElmnt.getElementsByTagName("website");
              Element websiteElement = (Element) websiteList.item(0);
              websiteList = websiteElement.getChildNodes();
              website[i].setText("Website = "
                      + ((Node) websiteList.item(0)).getNodeValue());
      
              category[i].setText("Website Category = "
                      + websiteElement.getAttribute("category"));
      
              layout.addView(name[i]);
              layout.addView(website[i]);
              layout.addView(category[i]);
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多