使用命名空間讀取XML。 請準確使用以下代碼,而不需要做任何更改。
<?xml version="1.0" encoding="UTF-8" standalone="no"?><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:aapi="http://rdf.alchemyapi.com/rdf/v1/s/aapi-schema#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:owl="http://www.w3.org/2002/07/owl#" xml:base="http://rdf.alchemyapi.com/rdf/v1/r/response.rdf">
<rdf:Description rdf:ID="d1dfa235105c033dec6dffdff63239d8b802087d9">
<rdf:type rdf:resource="http://rdf.alchemyapi.com/rdf/v1/s/aapi-schema#DocInfo"/>
<aapi:ResultStatus>OK</aapi:ResultStatus>
<aapi:Usage>By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html</aapi:Usage>
<aapi:URL/>
<aapi:Language>english</aapi:Language>
</rdf:Description>
<rdf:Description >
<aapi:Relevance>0.9683</aapi:Relevance>
<aapi:Name>Access control</aapi:Name>
<owl:sameAs rdf:resource="http://dbpedia.org/resource/Access_control"/>
<owl:sameAs rdf:resource="http://rdf.freebase.com/ns/guid.9202a8c04000641f8000000000051124"/>
</rdf:Description>
對於上述XML,您可以使用以下良好的Java代碼。 我建議你不要在谷歌這個代碼的測試前再通過自己的搜索:
import javax.xml.parsers.*;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = docBuilder.parse(new InputSource(new StringReader(strAbstractRdf)));
NodeList nl = doc.getElementsByTagNameNS("*","Description"); //the tag name
for (int kk=0;kk< nl.getLength(); kk++)
{
Node eDes = nl.item(kk);
if(eDes.getNodeType() == Node.ELEMENT_NODE)
{
Element eDescrition = (Element)eDes;
NodeList nlTermName= eDescrition.getElementsByTagNameNS("*","Relevance");
if(nlTermName.getLength() > 0)
{
Element eTermName =(Element) nlTermName.item(0);
System.out.println(eTermName.getTextContent());
}
}
}
爲了澄清,這是字符串「http://example.com/AttribElemClashes」,我想在這種情況下 - 謝謝 – Rob 2011-05-11 09:19:19