gpt4 book ai didi

java - 解码 xml 时忽略前缀(命名空间)

转载 作者:行者123 更新时间:2023-11-30 06:40:38 29 4
gpt4 key购买 nike

我有这个 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:不鼓励在 XXHeader 类中使用 @XML** 注释。

最佳答案

我可以使用 StreamReaderDelegate 来完成此操作,如上所述 here :

public class XXHeaderXMLReader
extends StreamReaderDelegate
{

public XXHeaderXMLReader(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, XXHeader.class).getValue();
System.out.println(xxHeader);
break;
}
}
}
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
catch (JAXBException e)
{
e.printStackTrace();
}

关于java - 解码 xml 时忽略前缀(命名空间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429213/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com