我试图在office xml中搜索特定节点。我正在使用wgxpath。这是我的代码。但每次返回空结果。可能是wgxpath doesn't work with namespaces(虽然它接受nsResolver作为参数)
Word.run(function (ctx) {
var xml = ctx.document.body.getOoxml();
ctx.sync().then(function () {
try {
var parser = new DOMParser();
var doc = parser.parseFromString(xml, "text/xml");
var win = { 'document': doc };
wgxpath.install(win);
var nsResolver = doc.createNSResolver(doc.ownerDocument == null ? doc.documentElement : doc.ownerDocument.documentElement);
var result = doc.evaluate("/pkg:package/pkg:part/pkg:xmlData/w:styles/w:docDefaults/w:pPrDefault/w:pPr/w:spacing", doc, nsResolver, win.XPathResult.ANY_TYPE, null);
var items = [];
try {
var item = result.iterateNext();
while (item) {
items.push(item);
item = result.iterateNext();
}
}
catch (e) {
reject(e);
}
resolve(items);
});
});
我还尝试了另一个简单的xml示例:
var parser = new DOMParser();
var test = "<pkg:count xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:a>1</pkg:a></pkg:count>";
var doc = parser.parseFromString(test, "text/xml");
var win = { 'document': doc };
wgxpath.install(win);
var nsResolver = function(prefix) {
var ns = {
'pkg': 'http://schemas.microsoft.com/office/2006/xmlPackage'
};
return ns[prefix] || null;
}
var result = doc.evaluate('/pkg:count/pkg:a', doc, nsResolver, win.XPathResult.ANY_TYPE, null);
结果相同:返回前缀为空的结果,但如果我删除前缀,则评估有效。
如何在office add ins中使用命名空间评估xml?还有其他方法吗?我曾尝试使用ActiveXObject(&#34; Microsoft.XMLDOM&#34;),但得到&#34;无法创建对象&#34;异常。