gpt4 book ai didi

java - 如何使用 Xstream 从 xml 中删除 namespace 前缀?

转载 作者:行者123 更新时间:2023-12-02 05:57:54 41 4
gpt4 key购买 nike

我有不同的 xml 文件,具有不同的命名空间例如 - oa、ns2、p...等

我希望在将 xml 转换回 java 对象时忽略 namespace 。或者我希望在将 xml 转换为对象时从 xml 中删除命名空间。

我的示例 xml 数据是

<oa:ApplicationArea>
<oa:Sender>
<oa:LogicalId>Volvo</oa:LogicalId>
<oa:Component>DVLA</oa:Component>
<oa:Task>ReceiveKeeper</oa:Task>
<oa:MessageCode>MS1</oa:MessageCode>
<oa:AuthorizationId>SKARUPAI</oa:AuthorizationId>
<oa:OrganisationLevel>50</oa:OrganisationLevel>
</oa:Sender>
<oa:CreationDateTime>2013-08-31T12:00:00</oa:CreationDateTime>
<oa:BODId>123456789</oa:BODId>
</oa:ApplicationArea>
<p:DataArea>
<oa:Sync confirm="Always">
<oa:SyncCriteria expressionLanguage="XPath">
<oa:SyncExpression action="Add"></oa:SyncExpression>
</oa:SyncCriteria>
</oa:Sync>
</p:DataArea>

下面是我使用 Xstream 将上述 xml 转换为 java 的代码示例。

public static void main(String[] args) throws Exception {
FileReader fileReader = new FileReader("C:/kspace/xstream/src/input.out.xml"); // load our xml file
XStream xstream = new XStream(); // init XStream
// Determine type of message(Eg. 'EM1') and put the corresponding value from hashmap to a String.
// Pass the string to xstream.alias(stringnamewhichwasset, xmlRoot.class)

String interfaceMessageId = "MS1";
String xmlRootTagName = (String) messages.get(interfaceMessageId);

xstream.registerConverter(new XMLDateConverter());
xstream.alias(xmlRootTagName, RootType.class);
xstream.aliasField("ApplicationArea", RootType.class, "applicationArea");
xstream.aliasField("DataArea", RootType.class, "dataArea");

xstream.alias("ApplicationArea", ApplicationArea.class);
xstream.aliasField("Sender", ApplicationArea.class, "sender");
xstream.aliasField("CreationDateTime", ApplicationArea.class, "creationDateTime");
xstream.aliasField("BODId", ApplicationArea.class, "bodId");

xstream.alias("Sender", Sender.class);
xstream.aliasField("LogicalId", Sender.class, "logicalId");
xstream.aliasField("Component", Sender.class, "component");
xstream.aliasField("Task", Sender.class, "task");
xstream.aliasField("MessageCode", Sender.class, "messageCode");
xstream.aliasField("AuthorizationId", Sender.class, "authorizationId");
xstream.aliasField("OrganisationLevel", Sender.class, "organisationLevel");......
......

有什么办法可以用 Xstream 做到这一点吗?

最佳答案

尝试使用StaxDriver后终于得到了解决方案。这就是我所做的。

QNameMap qmap = new QNameMap();
qmap.setDefaultNamespace("http://www.somename.com/xyz");
qmap.setDefaultPrefix("");
StaxDriver staxDriver = new StaxDriver(qmap);
XStream xstream = new XStream(staxDriver);

像这样创建 xstream 对象将在解析时忽略 namespace 前缀。到目前为止,我已成功删除所有命名空间前缀。

关于java - 如何使用 Xstream 从 xml 中删除 namespace 前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22912444/

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