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

时间:2014-04-07 12:28:57

标签: java xml namespaces xml-namespaces xstream

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

的xml文件

我希望在将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做到这一点吗?

1 个答案:

答案 0 :(得分:1)

最后在尝试使用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对象将在解析时忽略名称空间前缀。 到目前为止,我已成功删除所有名称空间前缀。