将xml字符串转换为Java对象

9

我有以下的xml字符串。我想将其转换为一个Java对象,将每个标签映射到该对象的字段。最好是可以引入与标签名称不同的字段名称。我应该如何做?我正在寻找JAXB的解决方案,但仍然对“ns4:response”和嵌套标签等部分感到困惑。谢谢您提前的帮助。

<ns4:response>
    <count>1</count>
    <limit>1</limit>
    <offset>1</offset>
    <ns3:payload xsi:type="productsPayload">
        <products>
            <product>
                <avgRating xsi:nil="true"/>
                <brand>Candie's</brand>
                <description>
                    <longDescription>
                    long descriptions
                    </longDescription>
                    <shortDescription>
                    short description
                    </shortDescription>
                </description>
                <images>
                    <image>
                        <altText>alternate text</altText>
                        <height>180.0</height>
                        <url>
                        url
                        </url>
                        <width>180.0</width>
                    </image>
                </images>
                <price>
                    <clearancePrice xsi:nil="true"/>
                    <regularPrice xsi:nil="true"/>
                    <salePrice>28.0</salePrice>
                </price>
            </product>
        </products>
    </ns3:payload>
</ns4:response>

还有,我能否自动把这个转换成Java类? - ghTvNath
2
可能是重复问题 http://stackoverflow.com/questions/779755/how-do-i-convert-xml-into-a-java-value-object - Nandkumar Tekale
标签嵌套标签,这让我感到困惑?还有 "ns4:response"。 - ghTvNath
希望这不是你对XML字符串的全部内容,因为命名空间前缀(ns4等)没有被定义,所以你不能用标准工具解析它。 - artbristol
1
在提问之前,你应该学会在 Stack Overflow 上搜索。 - Sikorski
4个回答

32

JAXB 是 Java 的标准化技术(JSR-222),用于将对象与 XML 互相转换。以下内容可能会对您有所帮助:

从字符串进行取消编组

在 JAXB 实现对字符串执行取消编组之前,您需要使用 StringReader 的实例将该字符串进行包装。

StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(sr);

不同的字段名和XML名称

您可以使用@XmlElement注释来指定元素的名称。默认情况下,JAXB查看属性.如果您想基于字段进行映射,则需要设置@XmlAccessorType(XmlAccessType.FIELD)

@XmlElement(name="count")
private int size;

命名空间

@XmlRootElement@XmlElement注解还允许您在需要的地方指定命名空间限定。

@XmlRootElement(namespace="http://www.example.com")
public class Response {
}

更多信息


有时候你需要一个人提供你所需要的东西!非常感谢Blaise! - Soroush Khosravi

2
JAXB是一个不错的选择。如果您有此文档的XSD文件,那么这将非常容易。JAXB可以为指定的模式生成Java代码。 如果您没有XSD文件,则需要自己准备Java类。查找JAXB教程并检查文档http://jaxb.java.net/tutorial/。 标签中的标签只是JAXB中嵌套对象。 ns4是命名空间。JAXB支持命名空间 - 只需在文档中查找即可。您可以使用注释来引入与XML标记不同的字段名称。遵循文档。

2
如果您已经拥有XML,并且有多个属性,您可以按照以下方式处理:
    String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
    <nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
    <nomCiudad>Pereira</nomCiudad></ciudads>";
    DocumentBuilder db = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(output));

    Document doc = db.parse(is);
    NodeList nodes = ((org.w3c.dom.Document) doc)
        .getElementsByTagName("ciudad");

    for (int i = 0; i < nodes.getLength(); i++) {           
        Ciudad ciudad = new Ciudad();
        Element element = (Element) nodes.item(i);

        NodeList name = element.getElementsByTagName("idCiudad");
        Element element2 = (Element) name.item(0);
        ciudad.setIdCiudad(Integer
            .valueOf(getCharacterDataFromElement(element2)));

        NodeList title = element.getElementsByTagName("nomCiudad");
        element2 = (Element) title.item(0);
        ciudad.setNombre(getCharacterDataFromElement(element2));

        ciudades.getPartnerAccount().add(ciudad);
    }
    }

    for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
    System.out.println(ciudad1.getIdCiudad());
    System.out.println(ciudad1.getNombre());
    }

方法getCharacterDataFromElement是:

    public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
    CharacterData cd = (CharacterData) child;

    return cd.getData();
    }
    return "";
    }

1
如果您拥有上述XML的XSD文件, 我建议您使用Jaxb。 JAXB可以从XML文件创建Java对象。 您需要使用jaxb的代码生成器首先生成Java类,该生成器以XSD作为输入,然后适当地序列化/反序列化这些XML文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接