删除Java中的子串

时间:2012-07-31 12:27:57

标签: java xml string xml-parsing

我正在尝试从原始字符串(这是一个xml文件)中删除搜索到的字符串。为此,我使用了replaceAll函数。但是我得到空的换行符,因为我使用“”来替换字符串。还有另一种删除字符串的方法吗?

        start =str.indexOf("<opts>");
        end =str.indexOf("</opts>");
        String removeStr = str.substring(start -6, end + 7);
        str = str.replaceAll(removeStr, "");

尝试:

    System.out.println("InitialString :="+str);
    int start = str.indexOf("<opts>");
    int end = str.lastIndexOf("</opts>"); //if \n is added, indent of tag<nos> changes
    str = str.substring(0, start ) + str.substring(end + 7, str.length());
    System.out.println("FinalString :="+str);

初始输入字符串:=

<data>
    <param>2</param>
    <unit>1</unit>
    <opts>
        <name>abc</name>
        <venue>arena0</venue>
    </opts>
    <opts>
        <name>xyz</name>
        <venue>arena1</venue>
    </opts>
    <nos>100</nos>
</data>

最终输出字符串:=

<data>
    <param>2</param>
    <unit>1</unit>

    <nos>100</nos>
</data>

2 个答案:

答案 0 :(得分:2)

你可以这样做;

int start = str.indexOf("<opts>");
int end = str.indexOf("</opts>\n");
str = str.substring(0, start - 6) + str.substring(end + 8, str.length());

答案 1 :(得分:2)

您没有在</opts>之后删除换行符号。当您执行end + 7时,您将其限制在</opts>的末尾,但可能会有\n或/和\r

如果您不想将其作为XML内容使用(将其解析为DOM Document并删除应使用removeChild删除的每个子项,并将其存储为将使用再次缩进你的XML)你可以进行后处理并在字符串替换后清空空行。


为了使用XML Document方法,您可以尝试:

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer        transformer  = transFactory.newTransformer();

// set some options on the transformer
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

// get a transformer and supporting classes
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
DOMSource    source = new DOMSource(xmlDoc);

// transform the xml document into a string
transformer.transform(source, result);

System.out.println(writer.toString()); 

样本来自:http://techxplorer.com/2010/05/20/indenting-xml-output-in-java/