简体   繁体   English

将 XML 文档复制到 Java 中的字符串变量中

[英]Copying an XML document into a String Variable in Java

I am trying to copy an entire XML document, tagnames/tagtypes irrelavant, into a String varible.我正在尝试将整个 XML 文档(标记名/标记类型无关)复制到字符串变量中。 Language to be used is Java.使用的语言是 Java。 I used ReadAllText to do it in C#, but I need to find an equivalent of that command in Java or another idea to be able to have the entire XML document as a String.我使用 ReadAllText 在 C# 中执行此操作,但我需要在 Java 中找到与该命令等效的命令,或者其他能够将整个 XML 文档作为字符串的想法I have been working on this for a while now.我已经为此工作了一段时间。 This is part of a bigger project.这是一个更大项目的一部分。 This is the only thing that is left to be done.这是唯一需要做的事情。 Any suggestions?有什么建议么? Thanks in Advance.提前致谢。

Well since this is java and not a scripting language, you will just need to use a scanner or file reader and read it line by line and append it into a single string.好吧,因为这是 java 而不是脚本语言,所以您只需要使用扫描仪或文件阅读器并逐行读取,然后将 append 转换为单个字符串。

This website has a great overview of file io in java.该网站对 java 中的文件 io 有一个很好的概述。 I actually learned a lot even after knowing about file io.即使在了解文件 io 之后,我实际上也学到了很多东西。

Here is a sample of what you could do:这是您可以执行的操作的示例:

private void processFile(File file)
{
        StringBuilder allText = new StringBuilder();
        String line;
        Scanner reader = null;
        try {
            FileInputStream fis = new FileInputStream(propertyFile);
            InputStreamReader in = new InputStreamReader(fis, "ISO-8859-1");
            reader = new Scanner(in);
            while(reader.hasNextLine() && !errorState)
            {
                line = reader.nextLine();
                allText.append(line);
            }
        } catch (FileNotFoundException e)
        {
            System.err.println("Unable to read file");
            errorState=true;
        } catch (UnsupportedEncodingException e) {
            System.err.println("Encoding not supported");
            errorState=true;
        }
        finally
        {
            reader.close();
        }
}

Try following code:试试下面的代码:

public String convertXMLFileToString(String fileName) 
{ 
    try { 
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
        InputStream inputStream = new FileInputStream(new File(fileName)); 
        org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream); 
        StringWriter stw = new StringWriter(); 
        Transformer serializer = TransformerFactory.newInstance().newTransformer(); 
        serializer.transform(new DOMSource(doc), new StreamResult(stw)); 
        return stw.toString(); 
    } catch (Exception e) { 
        e.printStackTrace(); 
    } 
    return null; 
}

use an StringWriter with a StreamResult .StringWriterStreamResult一起使用。

note, be very careful what you do with that string after that .请注意,之后要非常小心地处理该字符串 if you later write it to a stream/byte[] of some sort using the wrong character encoding, you will generate broken xml data.如果您稍后使用错误的字符编码将其写入某种流/字节[],您将生成损坏的 xml 数据。

I used a buffered Reader the last time I did this.我上次这样做时使用了缓冲阅读器。 Worked well.工作得很好。

String output = "";
try {
  FileInputStream is = new FileInputStream(file);
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  String line = "";
  while ((line = br.readLine()) != null) {
    output = output + line;
  }
  br.close();
  is.close();
} catch(IOException ex) {
  //LOG!
}

My original implementation was to use an actual buffer but I seemed to keep having issues with flushing the buffer so I went this way which is super easy.我最初的实现是使用一个实际的缓冲区,但我似乎一直在刷新缓冲区时遇到问题,所以我采用了这种方式,非常简单。

Many answers that get it almost, but not quite, correct.许多答案几乎但不完全正确。

  • If you use a BufferedInputStream and read lines, the result is missing line breaks如果您使用 BufferedInputStream 并读取行,则结果是缺少换行符
  • If you use a BufferedReader or a Scanner and read lines, the result is missing the original line breaks an the encoding may be wrong.如果您使用 BufferedReader 或 Scanner 并读取行,则结果会丢失原始换行符,并且编码可能是错误的。
  • If you use a Writer in a Result, the encoding may not match the source如果在 Result 中使用 Writer,编码可能与源不匹配

If you positively know the source encoding, you can do this:如果你肯定知道源编码,你可以这样做:

String file2string(File f, Charset cs) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
    InputStream in = new BufferedInputStream(new FileInputStream(f));
    int c;
    while ((c = in.read()) != -1)
        out.write(c);
    in.close();
    return out.toString(cs.name());
}

If you don't know the source encoding, rely on the XML parser to detect it and control the output:如果您不知道源编码,请依靠 XML 解析器来检测并控制 output:

String transform2String(File f, Charset cs) throws IOException,
        TransformerFactoryConfigurationError, TransformerException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.ENCODING, cs.name());
    ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
    t.transform(new StreamSource(new BufferedInputStream(
            new FileInputStream(f))), new StreamResult(out));
    return out.toString(cs.name());
}

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

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