我从博客中找到了以下代码,运行它时出现异常
XMLParseException:Start of root element expected. at 9th line.
任何人都可以解释为什么我会收到异常并建议将 String 转换为元素的任何其他方法吗?
String s = "Hello DOM Parser";
java.io.InputStream sbis = new java.io.StringBufferInputStream(s);
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
b.setNamespaceAware(false);
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilder db = null;
db = b.newDocumentBuilder();
doc = db.parse(sbis);
org.w3c.dom.Element e = doc.getDocumentElement();
最佳答案
要使用自定义标记创建 DOM Element
(我认为这是您想要的,但不能确定),您可以使用以下方法:
String customTag = "HelloDOMParser";
Document doc = documentBuilder.newDocument();
String fullName = nameSpacePrefix + ":" + customTag;
Element customElement = document.createElementNS(namespaceUri, fullName);
doc.appendChild(customElement);
我假设您知道命名空间 URI 和前缀(如果有)。如果您不使用命名空间,只需使用 createElement()
方法即可。
关于java - 将字符串转换为 w3c.dom.Element : XMLParseException:Start of root element expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5910288/