Java 双引号

标签 java

我需要找到一种方法来检查字符串中的双引号,以便将输出写入 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();
}

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

您还需要担心尖括号字符(“<”)。

但是,如果您不想将它们剥离出来,而是想在 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();
}

关于Java 双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307273/

相关文章:

java集合框架问题

java - 找不到合适的方法来替换(int,android.app.Fragment)

java - 用于 Java 的简单 Web 服务器和 MVC 框架

Java正则表达式,替换某些字符,除了

java - Kafka 消费者 - Java (0.9 API)

java.lang.ClassNotFoundException : com. mysql.jdbc.Driver - 不工作

Java:在静态方法中从父类(super class)创建子类的实例

java - 字节到整数

java - 有没有办法在iText(Java版本)中将矩形绘制到PdfPCell中?

java - 如何减少桌面应用程序中的 hibernate 内存使用?