如何使用Xstream从xml删除名称空间前缀?

编码努比

我有具有不同名称空间的不同xml文件 eg - oa, ns2, p...etc

我希望将xml转换回java对象时忽略名称空间。或者我希望在将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对象将在解析时忽略名称空间前缀。到目前为止,我已经能够成功删除所有名称空间前缀。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章