如何将xml标记存储为java中的数组

问题描述 投票:-1回答:3

在我的应用程序中,我正在解析一个xml文件。在xml文件中,我有50个同名question的标签,现在我想将所有作为问题命名的标签存储为数组....

保存的那些标签中,我只希望在文本视图中放置一个问题标签...。

如何执行此操作....请帮助我.....

java arrays xml-parsing
3个回答
4
投票
public class CustomHandler extends DefaultHandler {

    private ArrayList<String> questionList;
    private boolean questionBuffering;
    private StringBuilder sb;



    @Override
    public void startDocument() throws SAXException {
    questionList = new ArrayList<String>();
    } 

    @Override
    public void endDocument() throws SAXException {
    } 

    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (localName.equals("question")) {
            questionBuffering = true;
        }

    }


    @Override
    public void characters(char ch[], int start, int length) {
        if(questionBuffering) {
            sb.append(ch, start, length);
        }

    } 

    @Override
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        if (localName.equals("question")) {
            questionBuffering = false;
        questionList.add(sb.toString());
        }
    }

    public ArrayList<String> getResult() {
        return questionList;
        };
    }
}

0
投票

This answer似乎很容易适应您的需求。在示例中,问题存储在地图中,但是很容易将其更改为ArrayList或数组。


0
投票

您可以使用DOM解析器,这是DocumentBuilder类的link

一旦使用了parse中的DocumentBuilder方法并获得了Document,您就可以使用像这样的函数以NodeList的形式获取项目:

    public static NodeList getNodesByName(Document doc, String nodeName)
    {
            Element docEle = doc.getDocumentElement();
            NodeList list = docEle.getElementsByTagName(nodeName);
            return list;
    }

在您的情况下,您将传入通过解析XML创建的Document对象,然后将question作为您的nodeName

一旦有了NodeList,就可以使用for循环和.item()方法对其进行迭代。

            if(list != null && list.getLength() > 0) {
                for(int i = 0 ; i < list.getLength();i++) {
                    Element element = (Element)list.item(i);
                    String textVal = element.getFirstChild().getNodeValue();
                    //Once you get the value you can put it into your
                    //array or just use it here.
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.