Aspose.Word怎么获取 某段文本在文档中所在的位置

Aspose.Word怎么获取 某段文本在文档中所在的位置,这个位置包括:哪级标题、拿个段落、段落编号等详细信息

@ouchli 您可以使用查找/替换功能查找文本,然后获取包含匹配节点的节点,然后通过检查文档结构树您可以获得所需的信息。 请参阅我们的文档以了解有关 Aspose.Words 文档对象模型的更多信息:
https://docs.aspose.com/words/java/aspose-words-document-object-model/
https://docs.aspose.com/words/java/find-and-replace/

你好, 能给个只查找文本的示例吗, 只能找到替换的代码示例,没有找到查找的,谢谢。

@ouchli 您可以使用IReplacingCallback来实现此目的,例如,请参阅以下代码:

Document doc = new Document("C:\\Temp\\in.docx");
FindReplaceOptions opt = new FindReplaceOptions();
opt.setReplacingCallback(new SearchCallback());
doc.getRange().replace("Find Me", "", opt);
private static class SearchCallback implements IReplacingCallback
{
    @Override
    public int replacing(ReplacingArgs args) throws Exception {
            
        // Get the matched node.
        Node matchedNode = args.getMatchNode();
            
        // Do something with the matched node
        // ..................................
            
        // Do nothing with the matched text.
        return ReplaceAction.SKIP;
    }
}

没看懂,查找到的文本所在的位置返回值是什么呢

@ouchli 您可以使用以下代码来获取节点及其父节点:

private static class SearchCallback implements IReplacingCallback
{
    @Override
    public int replacing(ReplacingArgs args) throws Exception {
            
        // Get the matched node.
        Node matchedNode = args.getMatchNode();
        printNodeInfo(matchedNode);
            
        // Do nothing with the matched text.
        return ReplaceAction.SKIP;
    }
        
    private static void printNodeInfo(Node node)
    {
        System.out.println(NodeType.toString(node.getNodeType()));
        if(node.getParentNode()!=null)
        {
            System.out.println("Index of Node: " + node.getParentNode().indexOf(node));
            printNodeInfo(node.getParentNode());
        }
    }
}

您好,按照您的方式可以获取查找文本的位置信息,但是有一个问题,

在查找 图中红框内容:技术文件编号 时,返回的 位置信息为:Section 0, Body 4, Paragraph 7, Run 0。其中 的Body 索引是不对的,Body索引应该为0,返回的是4。应该是因为 在 Section中还有页眉页脚导致的索引有误,请问怎么避免这种情况呢?

@ouchli 你是对的,在你的例子中,BODY 是文档的第五个子元素。 所以Aspose.Words返回的索引是正确的。 如果需要获取同一类型节点中该节点的索引,可以修改代码如下:

private static void printNodeInfo(Node node)
{
    System.out.println(NodeType.toString(node.getNodeType()));
    if (node.getParentNode() != null)
    {
        System.out.println("Index of Node: " + node.getParentNode().getChildNodes(node.getNodeType(), false).indexOf(node));
        printNodeInfo(node.getParentNode());
    }
}

您好,还有一个问题

按照图中,我想获取红框中最后一个段落,用以下代码,获取的结果竟然是 Table里面的单元格内容,是因为这里将Table的单元格也当做段落处理了,请问怎么能准确获取到我需要的段落呢

Section section = (Section)doc.getChild(NodeType.SECTION, 1, true);
Body body = (Body)section.getChild(NodeType.BODY, 0, true);
Paragraph paragraph = (Paragraph)body.getChild(NodeType.PARAGRAPH, 2, true);

@ouchli 如果您只需要检查父节点的直接子节点,则应该在getChild方法的isDeep参数中传递false。 如果传递true,则指定类型的所有节点都将在其嵌套级别上独立考虑。