我正在编写XML解析器来解析这样的文档:
A
但是到目前为止我的解析代码有些麻烦:
<?xml version="1.0"?>
<world x="1920" y="1080">
<samples>2</samples>
<camera>
<origin x="0.0" y="50.0" z="-600.0"></origin>
<direction x= "0.0" y = "0.0" z = "0.0"></direction>
<FOV>30</FOV>
</camera>
<objects>
<plane>
<shader>Lambertian</shader>
<colour r="1.0" g="1.0" b="1.0"></colour>
<origin x="0.0" y="-80.0" z="0.0"></origin>
<normal x="0.0" y="-1.0" z="0.0"></normal>
</plane>
<sphere>
<shader>Lambertian</shader>
<colour r="0.0" g="1.0" b="0.0"></colour>
<origin x="-100.0" y="-40.0" z="-200.0"></origin>
<radius>40</radius>
</sphere>
<sphere>
<shader>Reflective</shader>
<origin x="0.0" y="-40.0" z="-200.0"></origin>
<radius>40</radius>
</sphere>
<sphere>
<shader>Transparent</shader>
<origin x="-40.0" y="-40.0" z="-300.0"></origin>
<radius>40</radius>
<ri>1.07</ri>
</sphere>
</objects>
<lights>
<light>
<origin x="100.0" y="200.0" z="-300.0"></origin>
<colour r="1.0" g="1.0" b="1.0"></colour>
</light>
<light>
<origin x="-100.0" y="300.0" z="-400.0"></origin>
<colour r="0.5" g="0.5" b="0.5">origin</colour>
</light>
</lights>
</world>
但是我得到了奇怪的结果,例如在File inputFile = new File(fileName);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
Element rootEle = doc.getDocumentElement();
String resX = rootEle.getAttribute("x");
String resY = rootEle.getAttribute("y");
int width = Integer.parseInt(resX);
int height = Integer.parseInt(resY);
RayTracer.setWorld(width, height);
NodeList nodes = rootEle.getChildNodes();
System.out.println(nodes.item(0).getNodeName());
Node sampler = nodes.item(1);
String samplesTemp = sampler.getTextContent();
System.out.println(samplesTemp);
int samples = Integer.parseInt(samplesTemp);
RayTracer.setSampler(samples);
Node camera = nodes.item(2);
我得到了#text,我不知道它来自哪里。对于System.out.println(nodes.item(0).getNodeName());
我得到了样本,item(1)
我得到#text和item(2)
我得到了相机。
答案 0 :(得分:0)
如果您的xml格式与您的示例完全相同,例如
<world x="1920" y="1080">
<samples>2</samples>
....
</world>
然后在开始标记#text
和开始标记<world>
之间有samples
。在这种情况下,有一个换行符和四个空格。这是<world>
之后的第一个节点。
也许你想要ignore the whitespaces。