我有一个像这样的 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。
最佳答案
尝试使用 xlm.replaceAll("\\++", "");
一次性替换一个或多个 +
。
关于java - 如何使用java修剪xml标签和值之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32256923/