繁体   English   中英

Java双引号

[英]Java Double Quote

我需要找到一种方法来检查字符串中的双引号,我可以将输出写入XML文档,然后用word打开。 我想出了如何查找像(')这样的单引号,但双引号在我的XML文档中引发了错误。

     private String checkForDoubleQuote(String l) {
    String newLine = new String();
    char d = '\"';


    for (int index=0;index < l.length();index++) {
        if(l.indexOf(8220)>-1 || l.indexOf(8221)>-1 ||
                 l.indexOf(34)>-1) {
            char c = l.charAt(index);     
             newLine += c;
        } else {
            char c = l.charAt(index);     
            newLine += c;
        }

    }
    System.out.println("new Line --> " + newLine);
    return newLine;
}

这是导致麻烦的XML字输出:(XML代码中的两个方框是x93和x94。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
<w:body>
<w:p>
<w:r>
<w:rPr>
<w:b/>
</w:rPr>
<w:t></w:t>
<w:t>x93That was close,x94 Lester said between breaths.</w:t>
</w:r>
</w:p>
</w:body>
</w:wordDocument>

如果你想从字符串中删除所有单引号和双引号字符,以及MS Office引用的那些愚蠢的特殊引号,这里有一个方法:

public static String stripQuote(String l) {
    StringBuffer newLine = new StringBuffer();

    for (int i=0; i<l.length(); i++) {
        char ch = l.charAt(i);
        if (ch==8220 || ch==8221 || ch=='\"' || ch=='\'') {
            //do nothing
        }
        else {
            newLine.append(ch);
        }
    }
    return newLine.toString();
}

您在示例中使用的代码在行的处理中构造了许多字符串。 这只构造一个。

您还需要担心anglebracket字符(“<”)。

但是,如果不是将它们剥离出来,而是希望在XML中正确编码它们,那么您可以这样做:

public static String encodeQuote(String l) {
    StringBuffer newLine = new StringBuffer();

    for (int i=0; i<l.length(); i++) {
        char ch = l.charAt(i);
        if (ch==8220 || ch==8221 || ch=='\"') {
            newLine.appent("&quot;");
        }
        else if (ch=='<') {
            newLine.appent("&lt;");
        }
        else if (ch=='>') {
            newLine.appent("&gt;");
        }
        else if (ch=='\'') {
            newLine.appent("&#39;");
        }
        else {
            newLine.append(ch);
        }
    }
    return newLine.toString();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM