Skip to content
Advertisement

Remove Child does not contain attribute value

I am practicing with XML DOM PHP parsing. I have such XML file (shorter version):

JavaScript

I created attribute with name “id” and value “2” for two Tag elements.

JavaScript

Now I would like to:

  1. Get only Tag elements which did not contain attribute ‘id=”2″‘;
  2. Get only Tag elements which contain only ‘id=”2″‘.

For first case I created such code. Don’t know exactly how to create second case.

JavaScript

Maybe someone can help me with second case? Thank you.

Advertisement

Answer

If I understand you source then you would like to add an id depending on the currency string. However your are using a language specific string. The language code would be a better option. It is defined and unique already.

DOMNode::getElementsByTagName() returns a node list, you could use foreach to iterate it. However the node list is “LIVE”. It reacts to changes on the nodes. This is an issue if you add/remove nodes. Using Xpath expressions avoids this and allows for more specific fetches.

More important, take a look at the DOMNode::$textContent property. It reads/writes the whole text inside of a node. For elements this includes any descendant text node.

Using this you can simplify the code:

JavaScript

Output:

JavaScript

Now to fetch the data with an specific id. I would expect that you would want the pozycja elements and its children.

DOMXpath::evaluate() can not just return node lists, but scalar values. It is not that much code:

JavaScript

Output:

JavaScript

However because the language code is already defined and unique, you could use it directly:

JavaScript

And if you need the “kurs_serdni” content for a specific currency code then you can do this with a single Xpath expression:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement