【问题标题】:parsing String to an arrayList element将 String 解析为 arrayList 元素
【发布时间】:2013-08-02 13:32:27
【问题描述】:

我的数据库中有这个字符串:

<user>
    <name>John</name>
    <surname>Shean</surname>
    <birthdate>1/1/1111</birthdate>
    <phone >(555) 444-1111</phone>
    <city>NY</city>
</user>

我需要解析它并添加到:

arrayList<User>.(User(name,surname,...))

最终应该是这样的:

user[1]={name="John",surname="Shena",...}

我使用了以下方法,但它不能正常工作。有没有人有办法做到这一点?

public User parseList(String array) {

    User user = new User();

    try {

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        URL u = new URL("xmldb:exist://192.168.1.71:8094/exist/xmlrpc/db/testDB/userInformation.xml");

        Document doc = builder.parse(u.openStream());

        NodeList nodes = doc.getElementsByTagName("user");

            Element element = (Element) nodes.item(0);

            user.setName(getElementValue(element, "name"));
            user.setSurname(getElementValue(element, "surname"));
            user.setBirthdate(getElementValue(element, "birthdate"));
            user.setPhone(getElementValue(element, "phone"));
            user.setCity(getElementValue(element, "city"));

            System.out.println(user);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return user;
}

protected String getElementValue(Element parent, String label) {
    return getCharacterDataFromElement((Element) parent.getElementsByTagName(label).item(0));
}

private String getCharacterDataFromElement(Element e) {
    try {
        Node child = e.getFirstChild();
        if (child instanceof CharacterData) {
            CharacterData cd = (CharacterData) child;
            return cd.getData();
        }
    } catch (Exception ex) {
    }
    return "";
}

【问题讨论】:

  • 看起来你有 xml。尝试谷歌搜索“java parse xml”
  • @user2642549 您是否尝试找出它为什么不起作用而不是要求新代码...如果新的第二个代码不起作用,您将要求第三个.. 编程不是像那样..如果您在代码中遇到问题,请尝试解决。那就是说..你的意思是It should looks like: user[1]={name="John",surname="Shena",...}
  • Stackoverflow 与其他 QA 网站伙伴不同,在这里,如果您犯错,其他人会开始对您大喊大叫。我只是让你知道 SO 是如何工作的。我没有否决你的问题,因为我知道这是一个真正的问题......我试图提供帮助,但无法得到我在评论中提到的路线。他们的我读到你对@Tala 的回复...

标签: java xml xml-parsing arraylist


【解决方案1】:

如果要解析 XML,可以使用 XML 解析器。 这可能会帮助您: Java:XML Parser

【讨论】:

    【解决方案2】:

    1 - 为您的使用类建模:

    package com.howtodoinjava.xml.sax;
    
    /**
     * Model class. Its instances will be populated using SAX parser.
     * */
    public class User
    {
        //XML attribute id
        private int id;
        //XML element name
        private String Name;
        //XML element surname
        private String SurName;
        //...
    
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return Name;
        }
        public void setName(String Name) {
            this.Name = Name;
        }
        public String getSurName() {
            return SurName;
        }
        public void setSurName(String SurName) {
            this.SurName = SurName;
        }
    
        // [...]
    
        @Override
        public String toString() {
            return this.id + ":" + this.Name +  ":" +this.SurName ;
        }
    }
    

    2 - 通过扩展 DefaultParser 构建处理程序

    package com.howtodoinjava.xml.sax;
    
    import java.util.ArrayList;
    import java.util.Stack;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    public class UserParserHandler extends DefaultHandler
    {
        //This is the list which shall be populated while parsing the XML.
        private ArrayList userList = new ArrayList();
    
        //As we read any XML element we will push that in this stack
        private Stack elementStack = new Stack();
    
        //As we complete one user block in XML, we will push the User instance in userList
        private Stack objectStack = new Stack();
    
        public void startDocument() throws SAXException
        {
            //System.out.println("start of the document   : ");
        }
    
        public void endDocument() throws SAXException
        {
            //System.out.println("end of the document document     : ");
        }
    
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
        {
            //Push it in element stack
            this.elementStack.push(qName);
    
            //If this is start of 'user' element then prepare a new User instance and push it in object stack
            if ("user".equals(qName))
            {
                //New User instance
                User user = new User();
    
                //Set all required attributes in any XML element here itself
                if(attributes != null &amp;&amp; attributes.getLength() == 1)
                {
                    user.setId(Integer.parseInt(attributes.getValue(0)));
                }
                this.objectStack.push(user);
            }
        }
    
        public void endElement(String uri, String localName, String qName) throws SAXException
        {
            //Remove last added  element
            this.elementStack.pop();
    
            //User instance has been constructed so pop it from object stack and push in userList
            if ("user".equals(qName))
            {
                User object = this.objectStack.pop();
                this.userList.add(object);
            }
        }
    
        /**
         * This will be called everytime parser encounter a value node
         * */
        public void characters(char[] ch, int start, int length) throws SAXException
        {
            String value = new String(ch, start, length).trim();
    
            if (value.length() == 0)
            {
                return; // ignore white space
            }
    
            //handle the value based on to which element it belongs
            if ("name".equals(currentElement()))
            {
                User user = (User) this.objectStack.peek();
                user.setName(value);
            }
            else if ("surname".equals(currentElement()))
            {
                User user = (User) this.objectStack.peek();
                user.setSurName(value);
            }
        }
    
        /**
         * Utility method for getting the current element in processing
         * */
        private String currentElement()
        {
            return this.elementStack.peek();
        }
    
        //Accessor for userList object
        public ArrayList getUsers()
        {
            return userList;
        }
    }
    

    3 - 为 xml 文件编写解析器

    package com.howtodoinjava.xml.sax;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.XMLReaderFactory;
    
    public class UsersXmlParser
    {
        public ArrayList parseXml(InputStream in)
        {
            //Create a empty link of users initially
            ArrayList<user> users = new ArrayList</user><user>();
            try
            {
                //Create default handler instance
                UserParserHandler handler = new UserParserHandler();
    
                //Create parser from factory
                XMLReader parser = XMLReaderFactory.createXMLReader();
    
                //Register handler with parser
                parser.setContentHandler(handler);
    
                //Create an input source from the XML input stream
                InputSource source = new InputSource(in);
    
                //parse the document
                parser.parse(source);
    
                //populate the parsed users list in above created empty list; You can return from here also.
                users = handler.getUsers();
    
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
    
            }
            return users;
        }
    }
    

    4 - 测试解析器

    package com.howtodoinjava.xml.sax;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    
    public class TestSaxParser
    {
        public static void main(String[] args) throws FileNotFoundException
        {
            //Locate the file OR String
            File xmlFile = new File("D:/temp/sample.xml");
    
            //Create the parser instance
            UsersXmlParser parser = new UsersXmlParser();
    
            //Parse the file Or change to parse String
            ArrayList users = parser.parseXml(new FileInputStream(xmlFile));
    
            //Verify the result
            System.out.println(users);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多