Java 使用XPath解析XML字符串数据时出现问题
我试图使用XPath解析XML字符串,但只返回空值。有人知道我在下面显示的代码中可能出错的地方吗Java 使用XPath解析XML字符串数据时出现问题,java,xml,xpath,Java,Xml,Xpath,我试图使用XPath解析XML字符串,但只返回空值。有人知道我在下面显示的代码中可能出错的地方吗 public static void main(String[] args) { String content = "<imagesXML><Images><Image><ImageUID Scope='Public' Type='Guid' Value='{7f2535d0-9a41-4997-9694-0a4de569e6d9}'/><
public static void main(String[] args) {
String content = "<imagesXML><Images><Image><ImageUID Scope='Public' Type='Guid' Value='{7f2535d0-9a41-4997-9694-0a4de569e6d9}'/><CorbisID Scope='Public' Type='String' Value='42-15534232'/><Title Scope='Public' Type='String' Value='Animal'/><CreditLine Scope='Public' Type='String' Value='© Robert Llewellyn/Corbis'/><IsRoyaltyFree Scope='Public' Type='Boolean' Value='False'/><AspectRatio Scope='Public' Type='String' Value='1.500000'/><URL128 Scope='Public' Type='String' Value='http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg'/></Image></Images></imagesXML>";
InputSource source = new InputSource(new StringReader(content));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList list = null;
try {
list = (NodeList) xPath.evaluate("//URL128[@Value]", source,
XPathConstants.NODESET);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
for (int i = 0; i < list.getLength(); i++) {
System.out.println(list.item(i));
}
}
publicstaticvoidmain(字符串[]args){
字符串内容=”;
InputSource source=新的InputSource(新的StringReader(内容));
XPath=XPathFactory.newInstance().newXPath();
节点列表=null;
试一试{
list=(NodeList)xPath.evaluate(“//URL128[@Value]”,source,
XPathConstants.NODESET);
}捕获(例外情况除外){
System.out.println(例如getMessage());
}
对于(int i=0;i
System.out的输出是“value=[URL128:null]”,但它应该是我试图提取的URL:http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg
感谢您的帮助。如果您尝试更改XPath求值语句,请执行以下操作:
list = (NodeList)xPath.evaluate("//URL128[@Value]",
source, XPathConstants.NODESET);
为此:
list = (NodeList) xPath.evaluate("//URL128/@Value",
source, XPathConstants.NODESET);
注:
- 表达式
返回具有//URL128[@Value]
属性的所有Value
元素的列表URL123
- 表达式
返回源中每个//URL128/@Value
元素的URL128
属性列表Value
URL128
元素,但您要求的是NodeList
。您可以使用以下方法来简化:
String url = xPath.evaluate("//URL128/@Value", source);
谢谢,成功了。I get Value=”“是否有任何方法可以使用XPath求值来删除Value=part?啊,找到它System.out.println(list.item(I.getTextContent())@c12:当然,如果您知道字符串主体中不会表示该字符串,则可以使用
String#replace
或String#replaceAll
执行此操作没关系,你的方式更好!