有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用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做到这一点


共 (1) 个答案

  1. # 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对象将在解析时忽略名称空间前缀。 到目前为止,我成功地删除了所有名称空间前缀