prewk/xml-string-streamer

Parser doesn't see attributes for tags that have a raw value

Closed this issue · 1 comments

When I have a node that looks like this:

...
        <Value Language="fr">
            <StringValue>My string</StringValue>
        </Value>
...

The parsing is correct, I basically get

$node = [
    '@attributes' => [
        'Language' => 'fr'
    ],
    'StringValue' => 'My string'
];

BUT when I have a node that have an attribute and a raw value (not his value in another tag, just the value), like this:

...
    <RefAttr>
        <AttrCode>MyAttribute</AttrCode>
        <RefValue Field1="70">VALUE1</RefValue>
        <RefValue Field1="30">VALUE2</RefValue>
    </RefAttr>
...

Then the parsing is missing the attributes, here's what I get in that case:

$node = [
    'AttrCode' => 'MyAttribute',
    'RefValue' => [
        'VALUE1',
        'VALUE2'
    ]
];

The @attributes entry is missing, I lose that value. Am I missing something?

prewk commented

The library itself just captures the nodes, it doesn't meddle with the attributes. It captures them as strings, which is what you'll get back when you do while ($xmlStr = $streamer->getNode()) {.

You can print out that string ($xmlStr) if you'd like and you'll see that the attributes are still there.

What you seem to be having problems with is SimpleXML.

Anyway, here's a working example that should illustrate how to use attributes in SimpleXML:

test.xml

<?xml version="1.0"?>
<root>
    <RefAttr>
        <AttrCode>MyAttribute</AttrCode>
        <RefValue Field1="70">VALUE1</RefValue>
        <RefValue Field1="30">VALUE2</RefValue>
    </RefAttr>
    <RefAttr>
        <AttrCode>MyAttribute</AttrCode>
        <RefValue Field1="60">VALUE1</RefValue>
        <RefValue Field1="40">VALUE2</RefValue>
    </RefAttr>
</root>

test.php

<?php
require_once("vendor/autoload.php");

$streamer = Prewk\XmlStringStreamer::createStringWalkerParser("test.xml");

while ($xmlStr = $streamer->getNode()) {
  // $xmlStr is here exactly one RefAttr node, in string format
  $node = simplexml_load_string($xmlStr);
  // $node is here a SimpleXMLElement of that RefAttr node

  echo (string)$node->RefValue[0]["Field1"] . "\n";
  echo (string)$node->RefValue[1]["Field1"] . "\n";
}

output

70
30
60
40