我有一个 xml 文件,如下所述:
<?xml version="1.0" encoding="UTF-8"?>
<Workbook>
<ExcelWorkbook
xmlns="urn:schemas-microsoft-com:office:excel"/>
<Worksheet ss:Name="Table 1">
<Table>
<Row ss:Index="7" ss:AutoFitHeight="0" ss:Height="12">
<Cell ss:Index="1" ss:StyleID="s05">
<ss:Data ss:Type="String"
xmlns="http://www.w3.org/TR/REC-html40">
<Font html:Size="9" html:Face="Times New Roman" x:Family="Roman" html:Color="#000000">
ABCD
</Font>
</ss:Data>
</Cell>
</Row>
如何使用 Java 中的 SAX 或 XPATH 提取数据(此处为“ABCD”)?
编辑1:
这是 XML-
<Table>
<Row ss:Index="74" ss:AutoFitHeight="0" ss:Height="14">
<Cell ss:Index="1" ss:MergeAcross="3" ss:StyleID="s29">
<ss:Data ss:Type="Number" xmlns="http://www.w3.org/TR/REC-html40">
0.00
</ss:Data>
</Cell>
<Cell ss:Index="15" ss:MergeAcross="5" ss:StyleID="s29">
<ss:Data ss:Type="Number" xmlns="http://www.w3.org/TR/REC-html40">
4.57
</ss:Data>
</Cell>
</Row>
最佳答案
该解决方案假设问题是如何根据行号和列号获取任何单元格的文本。
由于在输入文档中使用了命名空间,我花了一段时间才得到解决方案。显然,如果没有命名空间处理器和一个 hsa 来实现此目的的接口(interface)(没有默认值?),xpath 就无法解析合格的元素和属性,所以我找到了一种基于映射的实现 here并使用了它。
因此,假设您从源树中的链接中获得了该类,则以下代码将起作用。为了清楚起见,我将搜索模式分解为几个变量
public static String getCellValue(String filename, int rowIdx, int colIdx) {
// search for Table element anywhere in the source
String tableElementPattern = "//*[name()='Table']";
// search for Row element with given number
String rowPattern = String.format("/*[name()='Row' and @ss:Index='%d']", rowIdx) ;
// search for Cell element with given column number
String cellPattern = String.format("/*[name()='Cell' and @ss:Index='%d']", colIdx) ;
// search for element that has ss:Type="String" attribute, search for element with text under it and get text name
String cellStringContent = "/*[@ss:Type='String']/*[text()]/text()";
String completePattern = tableElementPattern + rowPattern + cellPattern + cellStringContent;
try (FileReader reader = new FileReader(filename)) {
XPath xPath = getXpathProcessor();
Node n = (Node)xPath.compile(completePattern)
.evaluate(new InputSource(reader), XPathConstants.NODE);
if (n.getNodeType() == Node.TEXT_NODE) {
return n.getNodeValue().trim();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static XPath getXpathProcessor() {
// this is where the custom implementation of NamespaceContext is used
NamespaceContext context = new NamespaceContextMap(
"html", "http://www.w3.org/TR/REC-html40",
"xsl", "http://www.w3.org/1999/XSL/Transform",
"o", "urn:schemas-microsoft-com:office:office",
"x", "urn:schemas-microsoft-com:office:excel",
"ss", "urn:schemas-microsoft-com:office:spreadsheet");
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(context);
return xpath;
}
调用:
System.out.println(getCellValue("C://Temp/xx.xml", 7, 1));
产生所需的输出
关于Java : Parsing xml file using SAX/XPATH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36529402/