2

I was using that example, but a bug occured Get line number from xml node - java

It works great, but fails on the following cases:

<activity
    android:name=".Main2Activity"
    android:label="@string/title_activity_main2"
    android:theme="@style/AppTheme.NoActionBar" />

So if a node is written on a few lines, it returns the last line. For the provided example it will return 4, but not 1. Does anybody have any ideas for to fix it? Thanks

Community
  • 1
  • 1
Ivan
  • 361
  • 3
  • 16
  • Because it is in line 4 and not 1 - what you mean is that the text `android:theme="@style/AppTheme.NoActionBar"` is included in the node that starts in line 1 and that can be checked when searching for the desired text and find out which line has the least `<` before that text. – Smutje Sep 12 '16 at 11:32

1 Answers1

0

Before getting the line number , transform your xml usin gthe following snippet :

    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    tf.setOutputProperty(OutputKeys.METHOD, "xml");
    tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");


    StreamSource source = new StreamSource(new File("sourcefile.xml"));
    StreamResult result = new StreamResult(new File("formattedfile.xml"));

    tf.transform(source, result);

This snippet will format the xml such that wach node will appear on a new line. Finally supply the formattedfile.xml as the input to the get line number logic.

Also be careful that you do not have some nodes in your xml which are needed by you to come as new line as that will be counterintutive with this logic.

Rambler
  • 4,994
  • 2
  • 20
  • 27