簡體   English   中英

如何使用Java修剪xml標記和值之間的空格

[英]How to trim the spaces between xml tags and values using java

我有一個這樣的xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

這是實際的XML文件。 在我們的應用程序中,我們以字符串形式接收此xml。

但是由於某種原因,由於硬件問題,應用程序正在接收xml,如下所示。

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove+++</to>
<from>Jani+</from>
<heading>Reminder++++</heading>
<body>Don't forget me this weekend!</body>
</note>

在我的java方法中,我編寫了這樣的代碼,

//It will trim all the + in the xml.
if(xml.indexOf("[+]")!=-1)){
xml = xml.replaceAll("[+]","").trim();
}

得到的結果如下。

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove  </to>
<from>Jani </from>
<heading>Reminder    </heading>
<body>Don't forget me this weekend!</body>
</note>

我再次像這樣修改我的代碼。

//It will replace all the + and white spaces in the xml.
if(xml.indexOf("[+]")!=-1)){
xml = xml.replaceAll("[+ ]","").trim();
}

但是,這段代碼給了我如下結果。

<?xmlversion="1.0"encoding="ISO-8859-1"?>//here I lose the spaces. 
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

在這里,我丟失了<?xmlversion="1.0"encoding="ISO-8859-1"?>的空格。

xml主體的另一部分沒有問題。

    <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
    </note>

除了此<?xmlversion="1.0"encoding="ISO-8859-1"?>.

當我嘗試在應用程序中運行此代碼時,出現SAXParcerException:缺少空格...等。

如何准確地編寫代碼以獲取文件,

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

我的應用程序完全基於Jdk 1.4構建,Web服務器為tomcat。

也許你可以使用

if (xml.contains("+")) {
    xml = xml.replace("+", "");
}

代替

xml = xml.replaceAll("[+ ]","").trim();

使用jdk 1.4可以使用

if (xml.indexOf("+") != -1) {
    xml = xml.replace("+", "");
}

嘗試使用xlm.replaceAll("\\\\++", ""); 一次替換一個或多個+

看來您想刪除出現在"</"之前的所有"+" ,:

xml = xml.replaceAll("\\++<\", "<\");

這不會影響出現在其他位置的"+" ,例如:

<tag>Bill + Ted+++</tag>

會變成

<tag>Bill + Ted</tag>

暫無
暫無

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

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