Viewed   63 times

I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via

$element = $dom->getElementsByTagName('foo')->item(0);
foreach($element->childNodes as $node){
    $data[$node->nodeName] = $node->nodeValue;
}

However, what I'm trying to do, is from an XML like,

<stuff>
  <foo>
    <bar></bar>
      <value/>
    <pub></pub>
  </foo>
  <foo>
    <bar></bar>
    <pub></pub>
  </foo>
  <foo>
    <bar></bar>
    <pub></pub>
  </foo>
  </stuff>

iterate over every foo tag, and get specific bar or pub, and get values from there. Now, how do I iterate over foo so that I can still access specific child nodes by name?

 Answers

5

Not tested, but what about:

$elements = $dom->getElementsByTagName('foo');
$data = array();
foreach($elements as $node){
    foreach($node->childNodes as $child) {
        $data[] = array($child->nodeName => $child->nodeValue);
    }
}
Monday, November 21, 2022
 
wooopsa
 
2

Based on your $_SESSION comment to Mike C,

foreach( $outer_array as $outer_key => $inner_array ) 
{
   foreach( $inner_array as $key => $value ) 
   {
      $_SESSION[$outer_key.'-'.$key] = $value;
   }
}

You would need unique keys though or (for instance) 'BCD118' and 'ABC' would both be key 0 and so 'ABC' would be overwritten.

Edit You could append the $outer_key to the inner $key to get a unique $_SESSION key

This would produce key/value pairs

0-0 : ABC
0-1 : 1
0-2 : 2
1-0 : BCD118
1-1 : 1
2-2 : 9
Tuesday, October 11, 2022
 
patison
 
3

You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

Here's a basic kickoff example:

package com..q3154488;

import java.io.File;

public class Demo {

    public static void main(String... args) {
        File dir = new File("/path/to/dir");
        showFiles(dir.listFiles());
    }

    public static void showFiles(File[] files) {
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory: " + file.getAbsolutePath());
                showFiles(file.listFiles()); // Calls same method again.
            } else {
                System.out.println("File: " + file.getAbsolutePath());
            }
        }
    }
}

Note that this is sensitive to Error when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com..q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

    public static void main(String... args) throws Exception {
        Path dir = Paths.get("/path/to/dir");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());
        }
    }
}
Saturday, August 13, 2022
 
2

Ok, let’s try this complete example of use:

function CatRemove($myXML, $id) {
    $xmlDoc = new DOMDocument();
    $xmlDoc->load($myXML);
    $xpath = new DOMXpath($xmlDoc);
    $nodeList = $xpath->query('//category[@id="'.(int)$id.'"]');
    if ($nodeList->length) {
        $node = $nodeList->item(0);
        $node->parentNode->removeChild($node);
    }
    $xmlDoc->save($myXML);
}

// test data
$xml = <<<XML
<?xml version="1.0"?>
<details>
 <person>name</person>
 <data1>some data</data1>
 <data2>some data</data2>
 <data3>some data</data3>
 <category id="0">
  <categoryName>Cat 1</categoryName>
  <categorydata1>some data</categorydata1>
 </category>
 <category id="1">
  <categoryName>Cat 2</categoryName>
  <categorydata1>some data</categorydata1>
  <categorydata2>some data</categorydata2>
  <categorydata3>some data</categorydata3>
  <categorydata4>some data</categorydata4>
 </category>
</details>
XML;
// write test data into file
file_put_contents('untitled.xml', $xml);
// remove category node with the id=1
CatRemove('untitled.xml', 1);
// dump file content
echo '<pre>', htmlspecialchars(file_get_contents('untitled.xml')), '</pre>';
Monday, December 19, 2022
5

You need to import any node to append it to another document:

$departmentArray->item($i)->appendChild( $doc->importNode( $employee, true ) );
Thursday, December 22, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :