Hi
Thanks for your request. I suppose what you are calling “ID of Paragraph” is just a name of REF field at the end of the paragraph. (Press Alt+F9 to see these fields). If so, you can try using the following code to get these IDs:
// Open document.
Document doc = new Document("C:\\Temp\\aspose_demo.docm");
// Get all paragraphs.
NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true);
// Loop through all paragraphs in the docuemnt and get their IDs.
for (int i = 0; i <paragraphs.getCount(); i++)
{
Paragraph currentParagraph = (Paragraph) paragraphs.get(i);
System.out.printf("%d\t%s\n", i, GetParagraphId(currentParagraph));
}
/**
* Returst ID of the paragraph. If the paragraph does not have ID, returns an empty string.
*/
private static String GetParagraphId(Paragraph par)
{
// "Paragraph ID" and of REF field.
// So we need to find REF field in the paragraph.
NodeCollection starts = par.getChildNodes(NodeType.FIELD_START, true);
// If there are no fields return an empty string because the paragraph does not have any ID.
if (starts.getCount() <= 0)
return "";
// Search for start of REF field.
FieldStart refStart = null;
for (int i = 0; i <starts.getCount(); i++)
{
FieldStart start = (FieldStart) starts.get(i);
// Check field type. If this is start of REF field, stop searching.
if (start.getFieldType() == FieldType.FIELD_REF)
{
refStart = start;
break;
}
}
// If there are no REF field, return an empty string.
if (refStart == null)
return "";
// Now we shoudl get field code of REF field.
String refFieldCode = "";
Node currentNode = refStart;
while (currentNode != null &&
currentNode.getNodeType() != NodeType.FIELD_SEPARATOR &&
currentNode.getNodeType() != NodeType.FIELD_END)
{
if (currentNode.getNodeType() == NodeType.RUN)
refFieldCode += ((Run) currentNode).getText();
// Move to the next node.
currentNode = currentNode.getNextSibling();
}
// Field code of REF field looks like th efollowing:
// REF
// We need to get ref_field_name, we will use the following regular expression to achieve this.
Pattern regex = Pattern.compile("\\s*REF\\s+(\\S+)\\s+.+");
Matcher match = regex.matcher(refFieldCode);
match.find();
return match.group(1);
}
Hope this helps.
Best regards.