简体   繁体   English

使用java解析xml中的元素数组

[英]parsing an array of elements in xml using java

Here, I'm using SAX method for parsing array. 在这里,我使用SAX方法解析数组。 I'm facing an issue where I'm not able to write a generic code to parse an array type of xml. 我遇到一个问题,我无法编写通用代码来解析数组类型的xml。 I couldn't find a solution for generic way methodology to identify it as an array and iterate over it and store it in List 我找不到通用方法方法的解决方案,将其识别为数组并迭代并将其存储在List中

<bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

Any solution will help. 任何解决方案都会有帮 Thanks in advance 提前致谢

I use code below. 我使用下面的代码。 I got it from: https://github.com/niteshapte/generic-xml-parser 我得到了它: https//github.com/niteshapte/generic-xml-parser

public class GenericXMLParserSAX extends DefaultHandler {

    private ListMultimap<String, String> listMultimap = ArrayListMultimap.create();
    String tempCharacter;   
    private String[] startElements;
    private String[] endElements;

    public void setStartElements(String[] startElements) {
            this.startElements = startElements;
    }

    public String[] getStartElements() {
            return startElements;
    }

    public void setEndElements(String[] endElements) {
            this.endElements = endElements;
    }

    public String[] getEndElements() {
            return endElements;
    }

    public void parseDocument(String xml, String[] startElements, String[] endElements) {
            setStartElements(startElements);
            setEndElements(endElements);

            SAXParserFactory spf = SAXParserFactory.newInstance();
            try {
                    SAXParser sp = spf.newSAXParser();                      
                    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());                     
                    sp.parse(inputStream, this);
            } catch(SAXException se) {
                    se.printStackTrace();
            } catch(ParserConfigurationException pce) {
                    pce.printStackTrace();
            } catch (IOException ie) {
                    ie.printStackTrace();
            }
    }

    public void parseDocument(String xml, String[] endElements) {           
            setEndElements(endElements);

            SAXParserFactory spf = SAXParserFactory.newInstance();
            try {
                    SAXParser sp = spf.newSAXParser();                      
                    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());                     
                    sp.parse(inputStream, this);
            } catch(SAXException se) {
                    se.printStackTrace();
            } catch(ParserConfigurationException pce) {
                    pce.printStackTrace();
            } catch (IOException ie) {
                    ie.printStackTrace();
            }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            String[] startElements = getStartElements();

            if(startElements!= null){
                    for(int i = 0; i < startElements.length; i++) {
                            if(qName.startsWith(startElements[i])) {                                
                                    listMultimap.put(startElements[i], qName);
                            }
                    }       
            }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
            tempCharacter = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {                
            String[] endElements = getEndElements();

            for(int i = 0; i < endElements.length; i++) {
                    if (qName.equalsIgnoreCase(endElements[i])) {
                            listMultimap.put(endElements[i], tempCharacter);                
                    }
            }
    }

    public ListMultimap<String, String> multiSetResult() {            
            return listMultimap;
    }
}

You can create a custom Handler that extends DefaultHandler and use it to parse your XML and generate the List<Book> for you. 您可以创建一个扩展DefaultHandler的自定义Handler,并使用它来解析XML并为您生成List<Book>

The Handler will maintain a List<Book> and: 处理程序将维护List<Book>和:

  • every time it will encounter the book start tag, it will create a new Book 每次它会遇到book start标签,它都会创建一Book
  • every time it will encounter the book end tag, it will add this Book to the List. 每次都会遇到这本书结束标签时,它会增加这Book到列表中。

In the end it will be holding the complete list of Books and you can access it via its getBooks() method 最后它将保存完整的Books列表,您可以通过其getBooks()方法访问它

Assuming this Book class: 假设这本书课:

class Book {
    private String category;
    private String title;
    private String author;
    private String year;
    private String price;
    // GETTERS/SETTERS
}

You can create a custom Handler like this: 您可以像这样创建自定义处理程序:

class MyHandler extends DefaultHandler {

    private boolean title = false;
    private boolean author = false;
    private boolean year = false;
    private boolean price = false;

    // Holds the list of Books
    private List<Book> books = new ArrayList<>();
    // Holds the Book we are currently parsing
    private Book book;

    public void startElement(String uri, String localName,String qName, Attributes attributes) {

        switch (qName) {
            // Create a new Book when finding the start book tag
            case "book": {
                book = new Book();
                book.setCategory(attributes.getValue("category"));
            }
            case "title": title = true;
            case "author": author = true;
            case "year": year = true;
            case "price": price = true;
        }
    }

    public void endElement(String uri, String localName, String qName) {
        // Add the current Book to the list when finding the end book tag
        if("book".equals(qName)) {
            books.add(book);
        }
    }

    public void characters(char[] ch, int start, int length) {
        String value = new String(ch, start, length);

        if (title) {
            book.setTitle(value);
            title = false;
        } else if (author) {
            book.setAuthor(value);
            author = false;
        } else if (year) {
            book.setYear(value);
            year = false;
        } else if (price) {
            book.setPrice(value);
            price = false;
        }
    }

    public List<Book> getBooks() {
        return books;
    }
}

Then you parse using this custom Handler and retrieve the list of Books 然后使用此自定义处理程序进行解析并检索Books列表

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

MyHandler myHandler = new MyHandler();
saxParser.parse("/path/to/file.xml", myHandler);
List<Book> books = myHandler.getBooks();

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

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