how to remove Xml version string from String

2020-05-26 07:23发布

I have read Xml File using code given below-

  String XmlString = "";
  String resourcePath=FilePathHelper.getResourceFilePath(request);



        BufferedReader br = new BufferedReader(new FileReader(new  File(resourcePath+ "SubIndicatorTemplate.xml")));
        String line;
        StringBuilder sb = new StringBuilder();

        while((line=br.readLine())!= null){
            sb.append(line.trim());
        }

        XmlString=sb.toString();

Now i get XmlString sting in the format given below-

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Template><Caption Name="Book Details"/><Data Type="one"/><Titles><Title Name="Book no" Type="Numeric"/><Title Name="Book name" Type="Text"/></Titles></Template>

I want to remove <?xml version="1.0" encoding="UTF-8" standalone="no"?> from above string.So i have written code as

XmlString=XmlString.replaceAll("<?xml*?>", "").trim();

But still XmlString are same. So please help me to remove version information from XmlString.

标签: java
5条回答
我命由我不由天
2楼-- · 2020-05-26 07:55

Change your regular expression to

XmlString=XmlString.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
查看更多
别忘想泡老子
3楼-- · 2020-05-26 08:05

Another way would we to do it like this:

XmlString = XmlString.substring(XmlString.indexOf("<Template>"))

edit: indexOf() instead of firstIndexOf()

查看更多
▲ chillily
4楼-- · 2020-05-26 08:09
if(XmlString .contains("<?xml")){
  XmlString = XmlString.substring(XmlString.indexOf("?>")+2);
}
查看更多
smile是对你的礼貌
5楼-- · 2020-05-26 08:11
String xmlString = readXml();
int p1 = xmlString.indexOf("<?xml ");
int p2 = xmlString.indexOf("?>");
if ( p1 != -1 && p2 != -1 && p2>p1){
   xmlString=xmlString.substring(0,p1)+xmlString(p2+2);
}

private String readXml(){
   //TOTO from file or any-pipeline read,convert to String....
}
查看更多
叼着烟拽天下
6楼-- · 2020-05-26 08:20

substring with first index of '>' + 1 ( +1 to get to next char), wont it give you end of xml version? Though it is not clean way of doing this.

查看更多
登录 后发表回答