与Java一起学习XML解析,并正在测试程序中尝试尝试一下。所有测试系统。分支名称"分别为"。
为了纠正我开始调整,当然会进一步打破该程序。现在,我正在扔一个saxexception(我已经标记了我用评论缩小的行,尽管我不清楚saxexception的含义等)'似乎让她回到以前的状态。
这是现在的代码:
package uploaders;
import javax.swing.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.awt.EventQueue;
import java.io.*;
public class Test {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
JFileChooser chooser = new JFileChooser();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringBuilder xmlStringBuilder = new StringBuilder();
String appendage = "<?xml version="1.0"?><branch0><name>Branch Name</name></branch0>";
ByteArrayInputStream input = new ByteArrayInputStream(xmlStringBuilder.toString().getBytes("UTF-8"));
chooser.setCurrentDirectory(new File("."));
chooser.setMultiSelectionEnabled(false);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Test Results:");
System.out.println();
System.out.println(chooser.getSelectedFile().getPath());
Document doc = builder.parse(input); //originally org.w3c.dom.Document...this line is where SAXException is thrown.
Element root = doc.getDocumentElement();
NodeList children = root.getChildNodes();
System.out.println(root.getTagName());
xmlStringBuilder.append(appendage); //forgot to move this up too (thanks @Vihar)
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element) {
Element childElement = (Element) child;
System.out.println(childElement.getTagName());
System.out.println(childElement.getNodeValue());
System.out.println(childElement); }
}
}
}
}
对saxexception的任何帮助都非常感谢,之后我仍然需要弄清楚为什么"名称"元素返回" null",但首先是第一件事:)。
更新在评论中显示的是导致Saxexception的原因。但是,控制台仍在显示:
Test Results:
/Users/.../Documents/java/Test/./bin
branch0
name
null //I'm expecting "Branch Name"
[name: null] //and "[name: Branch Name]"
最后
childElement.getNodeValue() //needed + .toString() to work or:
childElement.getNodeValue().toString()
或
childElement.getTextContent()
问题在这里
ByteArrayInputStream input = new ByteArrayInputStream(xmlStringBuilder.toString().getBytes("UTF-8"));
您刚刚创建了StringBuilder(XMLStringBuilder)的空对象,并希望解析该编译器,因此编译器会抛出SAXParseException
但是您确实需要做这个
ByteArrayInputStream input = new ByteArrayInputStream(appendage.toString().getBytes("UTF-8"));
当您appendage
字符串包含实际XML信息
或执行此
xmlStringBuilder.append(appendage); //I have just changed the sequence of these lines in your code
ByteArrayInputStream input = new ByteArrayInputStream(xmlStringBuilder.toString().getBytes("UTF-8"));
Document doc = builder.parse(input);
希望这会有所帮助!
祝你好运!