我有这个XML:
<?xml version="1.0" encoding="UTF-8"?>
<s:XXMsg xmlns:s="com:sample:test:msg">
<s:Header>
<s:cpyCod>xxx</s:cpyCod>
<s:appCod>yyy</s:appCod>
</s:Header>
</s:XXMsg>
我希望将其解组到以下Java类中:
public class XXHeader
{
private String cpyCod;
private String appCod;
}
我写了这段代码:
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
try
{
XMLStreamReader streamReader = inputFactory
.createXMLStreamReader(Test.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
while (streamReader.hasNext())
{
int next = streamReader.next();
if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT
&& streamReader.getLocalName().equals("Header"))
{
JAXBContext context = JAXBContext.newInstance(XXHeader.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
XXHeader xxHeader = unmarshaller.unmarshal(streamReader, XXHeader.class).getValue();
System.out.println(xxHeader);
break;
}
}
我将XXHeader
的所有字段值都设为null
。但如果我确实更改了xml并删除了每个元素中的前缀s:
,那么我会得到正确的值。
如何在解组时忽略此前缀以获取正确的值?
PS:不鼓励在@XML**
课程中使用XXHeader
注释。
答案 0 :(得分:1)
我可以使用here提到的StreamReaderDelegate
来执行此操作:
public class XXHeaderXMLReader
extends StreamReaderDelegate
{
public SBIsoHeaderXMLReader(XMLStreamReader paramXMLStreamReader)
{
super(paramXMLStreamReader);
}
@Override
public String getAttributeNamespace(int paramInt)
{
return "";
}
@Override
public String getNamespaceURI()
{
return "";
}
}
并在上一代码中添加该行:
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
try
{
XMLStreamReader streamReader = inputFactory
.createXMLStreamReader(DocumentTest.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
while (streamReader.hasNext())
{
int next = streamReader.next();
if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT)
{
if (streamReader.getLocalName().equals("Header"))
{
JAXBContext context = JAXBContext.newInstance(XXHeader.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
XXHeaderXMLReader xxHeaderXMLReader = new XXHeaderXMLReader(streamReader);
XXHeader xxHeader =
unmarshaller.unmarshal(xxHeaderXMLReader, SBIsoHeader.class).getValue();
System.out.println(xxHeader);
break;
}
}
}
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
catch (JAXBException e)
{
e.printStackTrace();
}
答案 1 :(得分:0)
Here您可能会找到有关忽略命名空间的有用信息,或者您可以定义XML架构(带字段说明)并使用它而不是com:sample:test:msg
。