获取片段
您当前获取 XML 片段的方式导致名称空间声明丢失。在您的片段ns2
中不再是前缀,您只有一个带有冒号的元素名称(ns2:Person
)。这将导致命名空间感知解析器出现问题。下面的文章可能是您获取 XML 片段的更好方法:
处理您的用例
使用您拥有的 XML 片段,您可以创建一个XMLFilter
从 XML 元素中删除前缀的片段,然后利用 JAXBUnmarshallerHandler
进行解组。
演示
package forum11968399;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.XMLFilterImpl;
public class Demo {
private static final String xml = "<ns2:Person name='John' age='20' />";
public static void main(String[] args) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xmlReader = sp.getXMLReader();
XMLFilter xmlFilter = new MyXMLFilter(xmlReader);
JAXBContext context = JAXBContext.newInstance(PersonEntity.class);
Unmarshaller um = context.createUnmarshaller();
UnmarshallerHandler unmarshallerHandler = um.getUnmarshallerHandler();
xmlFilter.setContentHandler(unmarshallerHandler);
StringReader sr = new StringReader(xml);
xmlFilter.parse(new InputSource(sr));
PersonEntity p = (PersonEntity) unmarshallerHandler.getResult();
}
private static class MyXMLFilter extends XMLFilterImpl {
public MyXMLFilter(XMLReader xmlReader) {
super(xmlReader);
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
int colonIndex = qName.indexOf(':');
if(colonIndex >= 0) {
qName = qName.substring(colonIndex + 1);
}
uri = XML_NAMESPACE; //to prevent unknown XML element exception, we have to specify the namespace here
super.startElement(uri, localName, qName, attributes);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
int colonIndex = qName.indexOf(':');
if(colonIndex >= 0) {
qName = qName.substring(colonIndex + 1);
}
super.endElement(uri, localName, qName);
}
}
}
个人实体
package forum11968399;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="Person")
@XmlAccessorType(XmlAccessType.FIELD)
public class PersonEntity {
@XmlAttribute
private String name;
@XmlAttribute
private int age;
}