java 如何在android中使用DOM或SAX解析器从XML读取子节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16706266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:43:09  来源:igfitidea点击:

How to read the child nodes from XML using DOM or SAX parser in android

javaandroidxml-parsingsaxparserdomparser

提问by Giri

This is my XML.

这是我的 XML。

<Operations>
<Operation Name="OperationName1">Entity details1</Operation>
<Operation Name="OperationName2">Entity details2</Operation>
<Operation Name="OperationName3">Entity details3</Operation>
<Operation Name="OperationName4">Entity details4</Operation>
</Operations>

In this I need to read each child nodes as a string variable. Using DOM I am trying like this.

在这里,我需要将每个子节点作为字符串变量读取。使用 DOM 我正在​​尝试这样。

NodeList items = root.getElementsByTagName("Operation");

        for (int i=0;i<items.getLength();i++)
        {   
            Node item = items.item(i);

            NodeList properties = item.getChildNodes();

            for (int j=0;j<properties.getLength();j++){

                Node property = properties.item(j);

                    }               
         }

Now as for my understand the items is having all the child nodes now I need to store each child node like this.

现在,据我所知,项目拥有所有子节点,现在我需要像这样存储每个子节点。

String ch_node="<Operation Name="OperationName4">Entity details4</Operation>"

Is there any default method that will give me the child node xml or I need to create again with node name,value and atrributes?

是否有任何默认方法可以为我提供子节点 xml,或者我需要使用节点名称、值和属性再次创建?

I have tried with SAX parser also but do not know how to get.

我也尝试过 SAX 解析器,但不知道如何获得。

public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {       
    if (qName.equalsIgnoreCase("operation")) {     
        op_Name=attributes.getValue(0);
    }
}

public void characters(char[] ch, int start, int length)
        throws SAXException {        
}

public void endElement(String uri, String localName, String qName)
        throws SAXException {       
}

采纳答案by Evgeniy Dorofeev

You can try DOM and Transformer

你可以试试 DOM 和 Transformer

    Transformer tx = TransformerFactory.newInstance().newTransformer();
    tx.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("1.xml"));
    NodeList list = doc.getElementsByTagName("Operation");
    for (int i = 0; i < list.getLength(); i++) {
        DOMSource src = new DOMSource(list.item(i));
        StringWriter sr = new StringWriter();
        Result res = new StreamResult(sr);
        tx.transform(src, res);
        System.out.println(sr);
    }

output

输出

<Operation Name="OperationName1">Entity details1</Operation>
<Operation Name="OperationName2">Entity details2</Operation>
<Operation Name="OperationName3">Entity details3</Operation>
<Operation Name="OperationName4">Entity details4</Operation>

回答by Sanjaya Liyanage

try this

试试这个

String elemName;

public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {       
   elemName=qName;
}

public void characters(char[] ch, int start, int length)
        throws SAXException {  
if(elemName.equals("OperationName1")) {
 String OperationName1Text=new String(ch);
}     
}

public void endElement(String uri, String localName, String qName)
        throws SAXException {       
}

回答by Basim Sherif

Please take look at the code below, Here I have fetched a child node "description"

请看下面的代码,这里我获取了一个子节点“描述”

URL url;

try {

    url = new URL(urls);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc;
        doc = db.parse(url.openStream());
        doc.getDocumentElement().normalize();

        NodeList itemLst = doc.getElementsByTagName("item");
        nl = doc.getElementsByTagName(KEY_HEAD);

        Description = new String[itemLst.getLength()];// ........


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

            Node item = itemLst.item(i);
            if (item.getNodeType() == Node.ELEMENT_NODE) {
                Element ielem = (Element) item;

                NodeList description = ielem
                        .getElementsByTagName("description");

                Desc[i] = description.item(0).getChildNodes().item(0)
                        .getNodeValue();

            }

        }

    }
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (DOMException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}