我知道很多次都会问过这个问题,但即使阅读完之后我也无法解决这个问题。
问:我有一个xml,它有一个节点(GivenName)用命名空间(mpeg7)定义,并在根元素的顶部声明。 我想使用javax xpath使用xpath表达式(// EpisodeOf / @ crid)解析一个属性。只是为了清除代码工作时我从xml中删除此GivenName节点。
XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TVAMain xmlns="urn:tva:metadata:2010" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mpeg7="urn:tva:mpeg7:2008" publicationTime="2017-12-09T08:14:32Z" publisher="Gracenote, Inc." version="1"
xml:lang="EN"
xsi:schemaLocation="urn:tva:metadata:2010
http://developer.tmsapi.com/files/tva_metadata_3-1_v161.xsd
urn:tva:mpeg7:2008
http://developer.tmsapi.com/files/tva_mpeg7_2008.xsd">
<ProgramDescription>
<ProgramInformationTable>
<ProgramInformation fragmentId="416885331" programId="someid">
<BasicDescription>
<CreditsList>
<CreditsItem role="urn:mpeg:cs:RoleCS:2010:HOST" index="1">
<PersonName xml:lang="EN">
<mpeg7:GivenName xml:lang="EN">Azeb</mpeg7:GivenName>
</PersonName>
</CreditsItem>
</CreditsList>
<EpisodeOf type="Series" index="428" crid="crid://gn.tv/185326/SH007323210000"/>
</BasicDescription>
</ProgramInformation>
</ProgramInformationTable>
</ProgramDescription>
</TVAMain>
代码(在Kotlin中):
val xpath = XPathFactory.newInstance().newXPath()
xpath.namespaceContext = MyNamespaceContext()
val extractedValue = xpath.evaluate("",InputSource(StringReader(AboveXMLInStringVariable)), qName)}
class MyNamespaceContext : NamespaceContext {
override fun getNamespaceURI(prefix: String?): String {
println("checking for getnamespace")
if (prefix == null) {
throw IllegalArgumentException("No prefix provided!");
} else if (prefix.equals("mpeg7")) {
return "http://developer.tmsapi.com/files/tva_mpeg7_2008.xsd";
} else {
return XMLConstants.NULL_NS_URI;
}
}
override fun getPrefix(namespaceURI: String?): String {
return ""
}
override fun getPrefixes(namespaceURI: String?): MutableIterator<Any?>? {
return null
}
}
在xpath.evaluate函数上获取错误。
Caused by: org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 60; The prefix "mpeg7" for element ":GivenName" is not bound.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:466)
... 38 more
问题: 我尝试给它NameSpaceContext,但看起来它没有使用它。建议?
答案 0 :(得分:1)
有几个问题:
DocumentBuilderFactory.setNamespaceAware(true)
。urn:tva:metadata:2010
。getNamespaceURI()
正在为mpeg7
返回错误的值;它
应该返回urn:tva:mpeg7:2008
。