有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

在保存的标签中,我只想在文本视图中放置一个问号

如何执行此操作。。。。请帮帮我


共 (3) 个答案

  1. # 1 楼答案

    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;
            };
        }
    }
    
  2. # 2 楼答案

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

    使用DocumentBuilder中的parse方法并获取Document后,您可以使用以下函数将项目获取为NodeList

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

    在本例中,您将传入通过解析XML创建的文档对象,然后question作为nodeName

    一旦有了节点列表,就可以使用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.
                    }
                }
    
  3. # 3 楼答案

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