Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

java - How to get jaxb to Ignore certain data during unmarshalling

I have a xml structure "Filter" that get unmarshalled into in a java class called "Filter".

The XML state looks roughly like:

<filter>
  <propertyType>
    <propertyName>prop1</propertyName>
    <propertyValue>val1</propertyValue>
  </propertyType>
  <propertyType>
    <propertyName>prop2</propertyName>
    <propertyValue>val2</propertyValue>
  </propertyType>
</filter>

Ordinarily, it works great.

However, there are certain situations where one of these property values itself contains xml structure (see second propertyValue below):

<filter>
  <propertyType>
    <propertyName>prop1</propertyName>
    <propertyValue>val1</propertyValue>
  </propertyType>
  <propertyType>
    <propertyName>prop2</propertyName>
    <propertyValue><nodeA><nodeB>valB</nodeB></nodeA></propertyValue>
  </propertyType>
</filter>

The problem here is that after unmarshalling this structure, the propertyValue is null.

I would like to simply be able to have the unmarshalling ignore this xml-looking code and treat it as a simple string value.

Does anyone know how I can accomplish this? Thanks for any reply!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about the annotation of using "@XmlAnyElement"? You can get the instance of org.w3c.dom.Element. The text data should be able to be obtained by operating this instance.

class PropertyType {
    private String propertyName;
    // private String propertyValue; // comment out
    @XmlAnyElement(lax=true)
    private List<org.w3c.dom.Element> propertyValue; // Adding this
}

exsample of to get text data.

// It is assumed that the child node is one. 
org.w3c.dom.Node nd = propertyValue.get(0).getFirstChild();
while(true) {
    if (nd.hasChildNodes()) {
        nd = nd.getFirstChild();
    } else {
        System.out.println(nd.getNodeValue()); // this is text data
        break;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...