简体   繁体   中英

How to read special characters like \n from XML file in Java?

In my XML I have

<'nodeName'>separator=\\n <'/nodeName'>

I am using DOM Parser to parse the XML. When I read the Value in Java Code, I am getting the value as \\n . It is not treated as line break but instead a Character(\\n).

I am very new to XML Parsing and so I am not sure that what has to be done to get the value as line break instead of a character \\n

Adding few lines from my code. Sorry I cannot add complete code but I hope my question is clear and below lines of code can add some extra light to it.

DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = dBuilder.parse(file);                
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xPExprAdditionalInfo = xPath.compile("./nodeName");
String separator =  xPExprAdditionalInfo.evaluate(node);

Any help would be appreciated.

I hope below explanation clears your confusion:

Escape sequence \\n is not new line character in XML file. This is just a way how Java understands new lines.

New line character depends on under laying operating system. Find more detailed explanation here .

I think there are two solutions

1 . So for your problem you can try to replace the \\n characters with new line escape sequence.

separator.replaceAll("\\\\n", "\n");
  1. Have new lines in you XML if you have liberty to do so

     <'nodeName'>separator= <'/nodeName'> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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