如何打通JAXB XML解析特定元素?(How to get a particular elemen

2019-08-07 01:53发布

我已经使用JAXB来解析XML.How打通JAXB XML解析特定元素(即子节点),而不进行解析时元素作为节点。

<?xml version="1.0" encoding="UTF-8"?>
        <Header>
            <From>
            <Credential
                        domain="NetworkId"><Identity>ANXXXNNN</Identity>
            </Credential>
            </From>

            <To>
            <Credential
                        domain="NetworkId"><Identity>ANNNXXXXXT</Identity>
            </Credential>
            </To>

            <To>
            <Credential
                        domain="NetworkId"><Identity>BNNXXXT</Identity>
            </Credential>
            </To>
        </Header>

我做了解组这样的,它的工作原理fine.For的表现,我不想要的元素node.Is有任何其它的办法吗?

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc;
    doc = db.parse(file);
    NodeList node = (NodeList)doc.getElementsByTagName("TO");

   JAXBElement<ToType> element =  jaxbUnmarshaller.unmarshal(node.item(0),ToType.class);

对象模型是一样

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ToType", propOrder = {
    "credential"
})
public class ToType {

    @XmlElement(name = "Credential", required = true)
    protected CredentialType credential;


    public CredentialType getCredential() {
        return credential;
    }

    public void setCredential(CredentialType value) {
        this.credential = value;
    }

}

Answer 1:

的StAX(JSR-173)解析器(包含在JDK / JRE开始与Java SE 6)可以被使用。 然后你就可以提前XMLStreamReader从有到子节点,并解组。

import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        XMLInputFactory xif = XMLInputFactory.newFactory();
        StreamSource xml = new StreamSource("src/forum14358769/input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(xml);

        // Advance to the "To" element.
        while(xsr.hasNext()) {
            if(xsr.isStartElement() && "To".equals(xsr.getLocalName())) {
                break;
            }
            xsr.next();
         }

        // Unmarshal from the XMLStreamReader that has been advanced
        JAXBContext jc = JAXBContext.newInstance(ToType.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        ToType toType = unmarshaller.unmarshal(xsr, ToType.class).getValue();
    }

}

欲获得更多信息

  • http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html


Answer 2:

你将不得不做以下做代码JAXB解组 :

unmarshaler.unmarshal(source);

这将返回你,你会使用XJC命令生成的类的实例

然后,您可以访问使用Bean方法的任何财产。



文章来源: How to get a particular element through JAXB xml parsing?