簡體   English   中英

如何使用Xstream從xml中刪除名稱空間前綴?

[英]How to remove namespace prefix from xml using Xstream?

我有不同的名稱空間的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對象將在解析時忽略名稱空間前綴。 到目前為止,我已成功刪除所有名稱空間前綴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM