简体   繁体   English

在java中解析xml数据

[英]Parsing xml data in java

i have one requirement to get the data from the xml. 我有一个要求从xml获取数据。

String res; 字符串res;

the data will be in the string res as follows. 数据将在字符串res中,如下所示。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
  <id>QZhx_w1eEJ</id>
  <first-name>pratap</first-name>
  <last-name>murukutla</last-name>
</person>

i have to get the id and the first-name and last-name from this data and has to be stored in the variables id,first-name,last-name 我必须从这个数据中获取id和first-name和last-name,并且必须存储在变量id,first-name,last-name中

how to access the xml to get those details. 如何访问xml以获取这些详细信息。

You could use JAXB (JSR-222) and do the following. 您可以使用JAXB(JSR-222)并执行以下操作。 An implementation is included in Java SE 6. Java SE 6中包含一个实现。

Demo 演示

package forum10520757;

import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Person.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StringReader xml = new StringReader("<person><id>QZhx_w1eEJ</id><first-name>pratap</first-name><last-name>murukutla</last-name></person>");
        Person person = (Person) unmarshaller.unmarshal(xml);

        System.out.println(person.id);
        System.out.println(person.firstName);
        System.out.println(person.lastName);
    }

    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    static class Person {
        String id;

        @XmlElement(name="first-name")
        String firstName;

        @XmlElement(name="last-name")
        String lastName;
    }

}

Output 产量

QZhx_w1eEJ
pratap
murukutla

You can start with: 你可以从:

ByteArrayInputStream inputStream = 
    new ByteArrayInputStream(response.getBody().getBytes("UTF-8"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
Document doc = builder.parse(new InputSource(inputStream));

You can see an example in http://www.java2s.com/Code/Java/XML/XMLDocumentinformationbyDOM.htm 您可以在http://www.java2s.com/Code/Java/XML/XMLDocumentinformationbyDOM.htm中看到一个示例

Use a SAX or DOM parser that's built into Java. 使用内置于Java中的SAX或DOM解析器。 Parse the String into a DOM tree, walk the tree, get your values. 将String解析为DOM树,遍历树,获取值。

http://java.sun.com/xml/tutorial_intro.html http://java.sun.com/xml/tutorial_intro.html

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

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