2013-03-12 47 views
1

我有一个从网站具有多行文本节点像这样获取的XML文件的Java应用程序:打印多XML节点正确

<root> 
    <node>info</node> 
    <mlnode>some 
multi 
line 
text</mlnode> 
</root> 

我的代码目前看起来是这样的:

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml))); 
    NodeList nList = doc.getElementsByTagName("mlnode"); 
    Node nNode = nList.item(0); 

    System.out.println(nNode.getTextContent()); 

不幸的是,这段代码把我的多行内容放到一行中:somemultilinetext。我想保留线路中断。我希望在所有操作系统(主要是Windows和Linux)上都保留换行符。

我该怎么做?

编辑:这个问题是不是关于正确的缩进。只是保持节点内容的换行符。因为该节点的内容是配置文件的一部分,并且必须由换行符分隔,所以将换行符保留在原来的位置非常重要。
我不在乎正确的缩进(如果我这样做:我知道SO和其他论坛上有足够的资源来解释如何正确缩进)。

+0

我的问题是不是缩进。这只是关于节点文本中的换行符。我不关心正确的缩进。 – wullxz 2013-03-12 01:54:46

+0

您的代码适用于我,使用Java 1.7.0_17。它用保留的换行符打印文本内容。 – VGR 2013-03-12 02:16:51

+0

奇怪。我使用OpenJDK 1.7.0_09在Linux上进行了测试。也许它是平台依赖的?你的操作系统是什么? – wullxz 2013-03-12 02:51:31

回答

0

我发现了这个错误,它不在我发布在我的问题中的代码中。
问题出在获取网站内容的代码中,该网站是一个xml文件,并将其转换为字符串。我用下面的代码,改编自this问题:

URL url; 
InputStream is = null; 
DataInputStream dis; 
String line; 
String content 

try { 
    url = new URL("https://stackoverflow.com/"); 
    is = url.openStream(); // throws an IOException 
    dis = new DataInputStream(new BufferedInputStream(is)); 

    while ((line = dis.readLine()) != null) { 
     content += line; // I forgot to add the linebreak here! 
     // I added "content += System.getProperty("line.separator");" and it solved my problem 
    } 
} catch (MalformedURLException mue) { 
    mue.printStackTrace(); 
} catch (IOException ioe) { 
    ioe.printStackTrace(); 
} finally { 
    try { 
     is.close(); 
    } catch (IOException ioe) { 
     // nothing to see here 
    } 
} 

对不起,我没想到在其他类beeing所以我没那个代码添加到我的问题的问题。

0

换行符正在被解析并按原样输出。

您的源XML似乎没有Windows需要的两个行尾字符。我猜你必须找到换行符(“\ n”)并用回车换行符换行(“\ r \ n”)。

由于额外的“\ r”在Unix系统上显示为^ M,因此应该在JVM中检测到操作系统,确保它是Windows并进行更换。

0

您可以在以下

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml))); 
NodeList nList = doc.getElementsByTagName("mlnode"); 
Node nNode = nList.item(0); 
String value = nNode.getTextContent(); 

StringBuilder stb = new StringBuilder(); 
String [] strAry = value.split("\n"); 
for(int k = 0; k < strAry.length; k++){ 
    stb.append(strAry[k]); 
    stb.append(System.getProperty("line.separator")); 
} 
System.out.println(stb.toString()); 

这一变化的代码应该打印文本,因为你需要