我需要在 Java 应用程序中使用 XPath 表达式查询 XML 文档。我创建了以下类,它接受一个文件(XML 文档在本地硬盘上的位置)和一个 XPath 查询,并且应该返回对给定文档的给定查询的评估结果。
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class XPathResolver
{
public String resolveXPath(File xmlFile, String xpathExpr) throws XPathException, ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
return (String) expr.evaluate(doc, XPathConstants.STRING);
}
}
假设现在我有以下 XML 文档。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
<DocumentFormat>Email</DocumentFormat>
<FileFormat>PDF</FileFormat>
</Document>
评估 /Document/FileFormat 和 //FileFormat 返回 PDF(如预期)。
但是,现在假设一个带有命名空间前缀的文档,如下所示。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document xmlns:file="http://www.example.com/xml/file">
<DocumentFormat>Email</DocumentFormat>
<file:FileFormat>PDF</file:FileFormat>
</Document>
现在 /Document/FileFormat 返回 PDF,但 //FileFormat 不返回任何内容。
对于带有命名空间前缀的文档,为什么我的代码没有返回预期的输出,我该如何解决?
最佳答案
我用 JDK 1.7.0.51 试过你的例子,可以确认你的结果。起初这似乎有点奇怪,但是 DocumentBuilderFactory 的默认行为是不识别命名空间。
所以你必须首先打开它:
factory.setNamespaceAware(true);
然后对于第二个文档,XPath 表达式没有预期的结果。
您必须将表达式更改为:/Document/file:FileFormat 和 //file:FileFormat。
在最后一步,您必须注册 NamespaceContext实现,它将 XPath 表达式中使用的 namespace 前缀映射到 namespace URI。遗憾的是,没有默认实现。
public String resolveXPath(File xmlFile, String xpathExpr) throws XPathException, ParserConfigurationException, SAXException, IOException, XPathExpressionException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Turn namespace aware on
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
// Set the NamespaceContext
xpath.setNamespaceContext(new MyNamespaceContext());
XPathExpression expr = xpath.compile(xpathExpr);
return (String) expr.evaluate(doc, XPathConstants.STRING);
}
class MyNamespaceContext implements NamespaceContext {
private Map<String, String> ns;
private Map<String, String> nsReverted;
public MyNamespaceContext() {
ns = new TreeMap<String, String>();
// Default namespaces and prefixes according to the documentation
ns.put(XMLConstants.DEFAULT_NS_PREFIX, XMLConstants.NULL_NS_URI);
ns.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
ns.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
// Now our self defined namespace
ns.put("file", "http://www.example.com/xml/file");
nsReverted = new TreeMap<String, String>();
for(Entry<String, String> entry : ns.entrySet()) {
nsReverted.put(entry.getValue(), entry.getValue());
}
}
@Override
public String getNamespaceURI(String prefix) {
if(prefix == null) {
throw new IllegalArgumentException();
}
final String uri = ns.get(prefix);
return uri == null ? XMLConstants.NULL_NS_URI : uri;
}
@Override
public String getPrefix(String namespaceURI) {
if(namespaceURI == null) {
throw new IllegalArgumentException();
}
return nsReverted.get(namespaceURI);
}
@Override
public Iterator getPrefixes(String namespaceURI) {
return ns.keySet().iterator();
}
}
关于java - 具有 namespace 的文档的 Java XPath 解析器的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21727745/
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und
我正在使用Rails3.1并在一个论坛上工作。我有一个名为Topic的模型,每个模型都有许多Post。当用户创建新主题时,他们也应该创建第一个Post。但是,我不确定如何以相同的形式执行此操作。这是我的代码:classTopic:destroyaccepts_nested_attributes_for:postsvalidates_presence_of:titleendclassPost...但这似乎不起作用。有什么想法吗?谢谢! 最佳答案 @Pablo的回答似乎有你需要的一切。但更具体地说...首先改变你View中的这一行对此#
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我