由于xml文件中的空格,我遇到了问题。我想从xml读取数据,但由于节点之间的空格,我遇到了各种问题。
实施例
If a node has 4 childs, due to the spaces it shows 9 childs to the node.
So when I try to display node values in table, some columns without heading and without data are also created.
When I removed these spaces I read my file successfully without any problem.
那怎么解决这样的问题呢?因为我每次都无法从文件中删除空格,因为我读取了多个xml文件。因此,从每个文件中删除空格将是一项繁琐的工作。
Document doc;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(fp);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("parameter");
nodeName = name;
for (int temp = 0; temp < nList.getLength();temp++)
{
Node nNode = (Node) nList.item(temp);
Element eElement = (Element) nNode;
String upname1 = getTagValue("name", eElement);
System.out.println(nodeName+" UP: "+upname1);
if(upname1.equals(nodeName))
{
NodeList pvalList = eElement.getElementsByTagName("paramvalues");
for(int l=0; l< pvalList.getLength(); l++)
{
Node pNode = (Node) pvalList.item(l);
NodeList valList = pNode.getChildNodes();
for(int j=0; j<valList.getLength(); j++)
{
Node valNode = (Node) valList.item(j);
if(valNode.getNodeName().equals("value"))
{
NamedNodeMap att = valNode.getAttributes();
for(int s=0; s<att.getLength(); s++)
{
Node n1 = att.item(s);
System.out.println("len: "+att.getLength());
if(n1.getNodeName().equals("default"))
def = n1.getNodeValue();
if(n1.getNodeName().equals("actualvalue"))
aval = n1.getNodeValue();
}
}
}
}
}
}
我知道这是一个奇怪的问题,但在完成我的工作时会变得很烦人。
Plz帮助..谢谢..
答案 0 :(得分:0)
您可以尝试在字符串的左侧和右侧创建一个TRIM空格,而解析示例'John Smith'的文档变为'John Smith' | src:http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
public class Trims{
public static String ltrim(String s){
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))){
i++;
}
return s.substring(i);
}
public static String rtrim(String s){
int i = s.length() - 1;
while (i > 0 && Character.isWhitespace(s.charAt(i))){
i--;
}
return s.substring(0, i + 1);
}
public static void main(String[] args){
String s = " \t \r \n String with spaces \t \r \n ";
System.out.println(ltrim(s));
System.out.println(rtrim(s));
System.out.println(s.trim()); //trims both ends
}
或者找到一种不同的方式处理内容..利用DOMBuilder(http://www.java-tips.org/other-api-tips/jdom/dealing-with-mixed-content-whitespace-comments-text-child-elements-and.html)
// a builder takes a boolean value meaning validation mode:
DOMBuilder builder = new DOMBuilder(false);
// simply load the document::
Document document = builder.build(
new java.io.File("sample.xml"));
Element order = document.getRootElement();
// find an address tag:
Element address =
order.getChild("purchased-by").getChild("address");