无法使用JAXB从元素中检索完整文本

时间:2016-12-09 16:24:21

标签: java xml jaxb

我正在尝试使用JAXB的解组示例检索文本,但无法检索内部...标记。这是我的第一个问题,因此对缩进我的代码非常不确定,但在这里它是: LangFlag.java

    package IDJAXBParser;

    import java.util.List;

    import javax.xml.bind.annotation.XmlAnyElement;
    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;



    @XmlType( propOrder = { "name", "description", "match", "context" } )
    @XmlRootElement( name = "langFlag" )

    public class LangFlag
    {

        String name;

        public String getName()
        {
            return name;
        }

        @XmlAttribute( name = "name" )
        public void setName( String name )
        {
            this.name = name;
        }

        String description;

        public String getDescription()
        {
            return description;
        }

        @XmlElement( name = "description" )
        public void setDescription( String description )
        {
            this.description = description;
        }

        String context;

        @XmlAnyElement(BioHandler.class)
        public String getContext()
        {
            return context;
        }


        public void setContext( String context )
        {
            this.context = context;
        }
        List<String> match;

        public List<String> getMatch()
        {
            return match;
        }

        @XmlElement( name = "match" )
        public void setMatch( List<String> match )
        {
            this.match = match;
        }

        @Override
        public String toString()
        {
            StringBuffer str = new StringBuffer( "Name: " + getName() + "\n" );
           str.append("Description:" + getDescription() + "\n");
           str.append("Context:" + getContext() + "\n");
           str.append("Match:" + getMatch() + "\n");
           str.append("\n");
            return str.toString();
        }
    }

ListOfLangFlags.java

    package IDJAXBParser;

    import java.util.ArrayList;
    import java.util.List;

    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;

    @XmlRootElement( name = "listOfLangFlags" )
    public class ListOfLangFlags
    {
        List<LangFlag> listOfLangFlags;

        public List<LangFlag> getLangFlags()
        {
            return listOfLangFlags;
        }

        /**
         * element that is going to be marshaled in the xml
         */
        @XmlElement( name = "langFlag" )
        public void setLangFlags( List<LangFlag> listOfLangFlags )
        {
            this.listOfLangFlags = listOfLangFlags;
        }

        public void add( LangFlag langFlag )
        {
            if( this.listOfLangFlags == null )
            {
                this.listOfLangFlags = new ArrayList<LangFlag>();
            }
            this.listOfLangFlags.add( langFlag );

        }

        @Override
        public String toString()
        {
            StringBuffer str = new StringBuffer();
            for( LangFlag langFlag : this.listOfLangFlags )
            {
                str.append( langFlag.toString() );
            }
            return str.toString();
        }

    }

UnMarshalJAXVBComplete.java         包IDJAXBParser;

    import java.io.File;

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Unmarshaller;

    import IDJAXBParser.ListOfLangFlags;

    public class UnMarshalJAXVBComplete
    {
        public static void main( String[] args )
        {

            try
            {

                File file = new File( "testv1.xml" );
                JAXBContext jaxbContext = JAXBContext.newInstance( ListOfLangFlags.class );

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                ListOfLangFlags langFlags = (ListOfLangFlags)jaxbUnmarshaller.unmarshal( file );
                System.out.println( langFlags );

            }
            catch( JAXBException e )
            {
                e.printStackTrace();
            }

        }

    }

这是我的XML文档:

<listOfLangFlags>
<langFlag name="Lang Flag Name">
                                <description>Lang Flag Description</description>
                                <context begin="0" end="100">I am so <span class="locality">blue </span>
                                I'm greener than purple. </context>
                                <suggestions/>
                                <match>I am so</match>
                                <match>blue</match>
                            </langFlag>
        </listOfLangFlags>

BioHandler.java

package IDJAXBParser;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class BioHandler implements DomHandler<String, StreamResult> {

    private static final String BIO_START_TAG = "<context>";
    private static final String BIO_END_TAG = "</context>";

    private StringWriter xmlWriter = new StringWriter();

    public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
        xmlWriter.getBuffer().setLength(0);
        return new StreamResult(xmlWriter);
    }

    public String getElement(StreamResult rt) {
        String xml = rt.getWriter().toString();
        int beginIndex = xml.indexOf(BIO_START_TAG) + BIO_START_TAG.length();
        int endIndex = xml.indexOf(BIO_END_TAG);
        return xml.substring(beginIndex, endIndex);
    }

    public Source marshal(String n, ValidationEventHandler errorHandler) {
        try {
            String xml = BIO_START_TAG + n.trim() + BIO_END_TAG;
            StringReader xmlReader = new StringReader(xml);
            return new StreamSource(xmlReader);
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

}

任何帮助将不胜感激!提前致谢

1 个答案:

答案 0 :(得分:0)

以下是DomHandler实施,可在DOM objectString之间进行转换。

import java.io.StringReader;

import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class BioHandler implements DomHandler<String, DOMResult> {

    private StringBuilder buffer = new StringBuilder();

    public DOMResult createUnmarshaller(ValidationEventHandler errorHandler) {
        return new DOMResult();
    }

    public String getElement(DOMResult rt) {
        Node n = rt.getNode();
        Element ele = null;
        if (n instanceof Document) {
            ele = ((Document)n).getDocumentElement();
        } else if (n instanceof DocumentFragment) {
            ele = (Element)n.getChildNodes().item(0);
        }
        //StringBuilder sb = new StringBuilder(); //only capture the text under current node.
        if (ele != null && "context".equals(ele.getLocalName())) {
            try {
                NodeList nl = (NodeList)XPathFactory.newInstance().newXPath()
                        .compile("descendant::text()").evaluate(ele, XPathConstants.NODESET);
                int length = nl.getLength();
                for (int i = 0; i < length; i++) {
                    buffer.append(nl.item(i).getTextContent());
                }
            } catch (XPathExpressionException e) {
                throw new RuntimeException(e);
            }
        }
//for problem tracing
//System.err.println("BioHandler.getElement(), ele="+ele.getLocalName() +", result=["+result+"]");
        return buffer.toString();
    }

    public Source marshal(String n, ValidationEventHandler errorHandler) {
        try {
            String xml = "<context>" + n.trim() + "</context>";
            StringReader xmlReader = new StringReader(xml);
            return new StreamSource(xmlReader);
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}

在我的测试过程中,未知的<suggestions/> element由同一个对象处理。所以我将buffer声明为类变量并每次输出捕获的内容。