【发布时间】:2011-09-17 06:36:32
【问题描述】:
我试图了解我可能犯了什么错误但找不到解决方案。
公共静态文档 getXMLFromString(String xml) {
org.w3c.dom.Document 文档 = null;
尝试 {
DocumentBuilderFactory 工厂 = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
文档构建器;
builder = factory.newDocumentBuilder();
doc = (org.w3c.dom.Document) builder.parse(new InputSource(
新的 StringReader(xml)));
} 捕捉(SAXException e){
e.printStackTrace();
} 捕捉(IOException e){
e.printStackTrace();
} 捕捉(ParserConfigurationException e){
e.printStackTrace();
}
返回文件;
}
我确实导入了 org.w3c.dom.Document
我在这里调用这个方法:
私有节点 getAuthToken(SOAPMessage responseAuth) 抛出 SOAPException, TransformerException、ParserConfigurationException、IOException、 SAX 异常 { 字符串 s = indentXML(responseAuth.getSOAPPart().getContent()); 文档 doc = getXMLFromString(s); NodeList authTokenNodeList = doc.getElementsByTagName("authToken"); 返回 authTokenNodeList.item(0); }NodeList 为空。
在网上研究后,大家使用这段代码将字符串解析为文档。我没有任何异常,但是在调用方法 parse() 之后,doc 的值被设置为 [#document: null] DeferredDocumentImpl。
我正在使用 org.w3c.dom 中的所有内容。
xml 是一个包含
的字符串<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<context xmlns="urn:zimbra">
<session id="36" type="admin">36</session>
<change token="251"/>
</context>
</soap:Header>
<soap:Body>
<AuthResponse xmlns="urn:zimbraAdmin">
<authToken>...</authToken>
<lifetime>...</lifetime>
<a n="zimbraIsDomainAdminAccount">false</a>
<session id="36" type="admin">36</session>
</AuthResponse>
</soap:Body>
</soap:Envelope>
这是我在 SOAP 调用后构建字符串的方式:
String xml = indentXML(responseAuth.getSOAPPart().getContent());
我做错了什么?
这就是我想要以一种简单的方式做的事情:
StringBuilder soapResponse = new StringBuilder(...
...
...
);
org.w3c.dom.Document 文档 = null;
尝试 {
DocumentBuilderFactory 工厂 = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
文档构建器;
builder = factory.newDocumentBuilder();
doc = (org.w3c.dom.Document) builder.parse(new InputSource(
新的 StringReader(soapResponse.toString())));
} 捕捉(SAXException e){
e.printStackTrace();
} 捕捉(IOException e){
e.printStackTrace();
} 捕捉(ParserConfigurationException e){
e.printStackTrace();
}
NodeList authTokenNodeList = doc.getElementsByTagName("authToken");
节点 n = authTokenNodeList.item(0);
字符串 s = n.getNodeValue();
【问题讨论】:
-
文件的内容是什么,可变的xml是什么?
-
您能否像 Jon Skeet 在他的回答中所说的那样向我们展示您导入的完整代码
-
刚刚编辑了我的消息,谢谢大家的帮助,我真的不明白这是怎么回事。
-
如果 XML 来自文件,您是否尝试过使用 parse 方法从文件中读取它??
-
XML 是我在进行 SOAP 调用后收到的。 String xml = indentXML(responseAuth.getSOAPPart().getContent());
标签: java