[英]XML in string format to org.w3c.dom.Document in Java
I am trying to convert a samlResponse in string format to org.w3c.dom.Document to validate it. 我正在尝试将字符串格式的samlResponse转换为org.w3c.dom.Document进行验证。 But it yields null even though I have used couple of different ways.
但是即使我使用了几种不同的方法,它也会产生null。
One way is as below: Here even the inputStream is null. 一种方法如下:这里,即使inputStream为null。
BasicParserPool bpp = new BasicParserPool(); bpp.setNamespaceAware(true); Document doc= bpp.parse(new ByteArrayInputStream(samlResponse.getBytes())); Element responseElement = doc.getDocumentElement();
where the string samlResponse is as below (just a snippet): 字符串samlResponse如下所示(只是一个片段):
String samlResponse = "<saml2p:Response xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" Version=\"2.0\"> <saml2:Issuer etc etc
Any thoughts where I am going wrong? 有什么想法我要去哪里错吗?
BasicParserPool is an OpenSAML class, and I haven't used OpenSAML, so I can't say why it isn't working. BasicParserPool是一个OpenSAML类,并且我没有使用过OpenSAML,所以我不能说为什么它不起作用。
I can give you a simple alternative that works for me however. 我可以给你一个简单的选择,但是对我有用。
I convert Strings to org.w3c.dom.Document using javax.xml.parsers.DocumentBuilderFactory and javax.xml.parsers.DocumentBuilder: 我使用javax.xml.parsers.DocumentBuilderFactory和javax.xml.parsers.DocumentBuilder将字符串转换为org.w3c.dom.Document:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document result = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
where "xml" is the String to convert. 其中“ xml”是要转换的字符串。 There is some exception-catching that I have left out.
我遗漏了一些异常捕获功能。
The API is here: DocumentBuilder API API在这里: DocumentBuilder API
Hope this helps. 希望这可以帮助。
Hope this piece of below code helps 希望下面的这段代码对您有所帮助
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
*
* @author karthikeyan.s1
*/
public class Parser {
public Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(true);
dbf.setNamespaceAware(true);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
// Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
// Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
// Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.