Adiz
Adiz

Reputation: 21

How to find specific location of attribute in xml node

I have been trying to find the location of an attribute (line, column) in a specific xml node. I know i can reach the node and the attribute value by using XPATH or sax parser but havent found a way to locate the position of the attribute. Appreciate your help

Upvotes: 0

Views: 322

Answers (3)

Adiz
Adiz

Reputation: 21

I managed to do this using XMLDOM.

DOMParser = require('xmldom').DOMParser;


var parser = new DOMParser({locator:{}});
var content = parser.parseFromString(xmlContent, "text/xml");
var rootNode = this.parseXml(content.documentElement);
var attrs = rootNode .attributes || [];
for (var i = 0; i < attrs.length; i++) {
     var attr = attrs[i];
     var nColumn = attr.columnNumber;
     var nLine = attr.lineNumber;
}

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163322

The DOM parsers found in browsers typically don't make any location information available (AFAIK). If you're using a third-party SAX parser then you may be more lucky; but it all depends on the parser you are using. I'd be surprised to see location information at the individual attribute level, though: it's expensive to provide, and element-level information is more common.

Upvotes: 1

L Y E S  -  C H I O U K H
L Y E S - C H I O U K H

Reputation: 5080

For example, a sample XML file is:

<parents name='Parents'>
  <Parent id='1' name='Parent_1'>
    <Children name='Children'>
      <child name='Child_2' id='2'>child2_Parent_1</child>
      <child name='Child_4' id='4'>child4_Parent_1</child>
      <child name='Child_1' id='3'>child1_Parent_1</child>
      <child name='Child_3' id='1'>child3_Parent_1</child>
    </Children>
  </Parent>
  <Parent id='2' name='Parent_2'>
    <Children name='Children'>
      <child name='Child_1' id='8'>child1_parent2</child>
      <child name='Child_2' id='7'>child2_parent2</child>
      <child name='Child_4' id='6'>child4_parent2</child>
      <child name='Child_3' id='5'>child3_parent2</child>
    </Children>
  </Parent>
</parents>

Using XPath, you can do :

//Parent[@id='1']/Children/child/@name 

Output :

Child_2
Child_4
Child_1
Child_3

Upvotes: 0

Related Questions