-1

Possible Duplicate:
XML attribute vs XML element

What is the difference between snippet "A":

<root>
    <item id="1">
        <attr1> foo </attr1>
        <attr2> bar </attr2>
    </item>
</root>

and placing the "id" attribute within the element in snippet "B":

<root>
    <item>
        <id> 1 </id>
        <attr1> foo </attr1>
        <attr2> bar </attr2>
    </item>
</root>

and how would I add the attribute "id" when creating xml with PHP in snippet "A" assuming I can already create the format of snippet "B" just fine using DOM's createElement() and appendChild?

Thanks!

Community
  • 1
  • 1

3 Answers3

1

Use setAttribute to add the attribute to the DOM element:

$domNode->setAttribute("id", "youridvalue");

The only difference between the two is the syntax used to get the values back, and in one you're adding an attribute, the other you're adding a tag. Either works, I prefer attributes.

Alex
  • 7,320
  • 1
  • 18
  • 31
  • The difference is not merely syntactical. You can use a CDATA section inside an element, but not an attribute. Also the attribute should be unique across the whole document and is the subject of special processing: http://www.w3.org/TR/xml-id/#processing – Zecc Aug 09 '11 at 14:20
1

You can call $element->setAttribute($name, $value) after you have created the id element

H Hatfield
  • 881
  • 5
  • 9
1

"id" is an attribute in snippet "A" and a node in snippet "B". You can use setAttribute to add this.

FrankS
  • 2,374
  • 3
  • 26
  • 32
  • Thanks for this. I had no idea what they were or what they were called (thus I couldn't search for them). Apparently that is almost a crime on S.O. considering the downvotes. – IDLacrosseplayer Aug 09 '11 at 14:23