RSS

Most votes on xml questions 7

Most votes on xml questions 7. #61 Normalization in DOM parsing with java - how does it work? #62 Class 'DOMDocument' not found #63 How to generate XML file dynamically using PHP? #64 Are SVG parameters such as 'xmlns' and 'version' needed? #65 How to escape "&" in XML? #66 How to change line color in EditText #67 How to use XPath in Python? #68 google protocol buffers vs json vs XML #69 XPath to select element based on childs child value #70 XML Schema minOccurs / maxOccurs default values

Read all the top votes questions and answers in a single page.

#61: Normalization in DOM parsing with java - how does it work? (Score: 243)

Created: 2012-12-09 Last updated: 2020-07-20

Tags: java, xml, dom

I saw the line below in code for a DOM parser at this tutorial.

doc.getDocumentElement().normalize();

Why do we do this normalization ?
I read the docs but I could not understand a word.

Puts all Text nodes in the full depth of the sub-tree underneath this Node

Okay, then can someone show me (preferably with a picture) what this tree looks like ?

Can anyone explain me why normalization is needed?
What happens if we don’t normalize ?

#61 Best answer 1 of Normalization in DOM parsing with java - how does it work? (Score: 373)

Created: 2012-12-09 Last updated: 2013-05-14

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

#61 Best answer 2 of Normalization in DOM parsing with java - how does it work?(Score: 10)

Created: 2016-06-29 Last updated: 2018-07-26

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(<document></document>)
b) white spaces within start tag (<>) and end tag (</>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc…

See also original question in stackoverflow

#62: Class 'DOMDocument' not found (Score: 240)

Created: 2013-01-18 Last updated: 2016-06-06

Tags: php, xml, magento

I’ve found an error on a page in my Magento application; it always show this message error when I visit it:

Fatal error: Class ‘DOMDocument’ not found in /home/…/lib/Zend/Feed/Abstract.php on line 95

Can you give me a solution? I’m using magento 1.4.1.1.

#62 Best answer 1 of Class 'DOMDocument' not found (Score: 350)

Created: 2013-01-18 Last updated: 2020-08-03

You need to install the DOM extension. You can do so on Debian / Ubuntu using:

sudo apt-get install php-dom

And on Centos / Fedora / Red Hat:

yum install php-xml

If you get conflicts between PHP packages, you could try to see if the specific PHP version package exists instead: e.g. php53-xml if your system runs PHP5.3.

#62 Best answer 2 of Class 'DOMDocument' not found(Score: 185)

Created: 2016-03-01 Last updated: 2021-01-14

PHP 7.0:

  • Ubuntu: apt-get install php7.0-xml
  • CentOS / Fedora / Red Hat: yum install php70w-xml

PHP 7.1:

  • Ubuntu: apt-get install php7.1-xml
  • CentOS / Fedora / Red Hat: yum install php71w-xml

PHP 7.2:

  • Ubuntu: apt-get install php7.2-xml
  • CentOS / Fedora / Red Hat: yum install php72w-xml

PHP 7.3:

  • Ubuntu: apt-get install php7.3-xml
  • CentOS / Fedora / Red Hat: yum install php73w-xml

PHP 7.4:

  • Ubuntu: apt-get install php7.4-xml
  • CentOS / Fedora / Red Hat: yum install php74w-xml

PHP 8.0

  • Ubuntu: apt-get install php8.0-xml
  • CentOS 8 [with php:remi-8.0 enabled]: dnf install php-xml

See also original question in stackoverflow

#63: How to generate XML file dynamically using PHP? (Score: 240)

Created: 2009-01-28 Last updated: 2013-10-13

Tags: php, xml

I have to generate a xml file dynamically at runtime. Please help me in generating the below XML file dynamically using PHP.

<?xml version="1.0" encoding="UTF-8"?>
<xml>
 <track>
     <path>song1.mp3</path>
     <title>Track 1 - Track Title</title>
 </track>
 <track>
     <path>song2.mp3</path>
     <title>Track 2 - Track Title</title>
 </track>
 <track>
     <path>song3.mp3</path>
     <title>Track 3 - Track Title</title>
 </track>
 <track>
     <path>song4.mp3</path>
     <title>Track 4 - Track Title</title>
 </track>
 <track>
     <path>song5.mp3</path>
     <title>Track 5 - Track Title</title>
 </track>
 <track>
     <path>song6.mp3</path>
     <title>Track 6 - Track Title</title>
 </track>
 <track>
     <path>song7.mp3</path>
     <title>Track 7 - Track Title</title>
 </track>
 <track>
     <path>song8.mp3</path>
     <title>Track 8 - Track Title</title>
 </track>

#63 Best answer 1 of How to generate XML file dynamically using PHP? (Score: 361)

Created: 2009-01-28 Last updated: 2013-01-29

I’d use SimpleXMLElement.

<?php

$xml = new SimpleXMLElement('<xml/>');

for ($i = 1; $i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

Header('Content-type: text/xml');
print($xml->asXML());

#63 Best answer 2 of How to generate XML file dynamically using PHP?(Score: 184)

Created: 2009-01-28 Last updated: 2021-04-28

To create an XMLdocument in PHP you should instance a DOMDocument class, create child nodes and append these nodes in the correct branch of the document tree.

For reference you can read http://it.php.net/manual/en/book.dom.php

Now we will take a quick tour of the code below.

  • at line 2 we create an empty xml document (just specify xml version (1.0) and encoding (utf8))
  • now we need to populate the xml tree:
    • We have to create an xmlnode (line 5)
    • and we have to append this in the correct position. We are creating the root so we append this directly to the domdocument.
    • Note create element append the element to the node and return the node inserted, we save this reference to append the track nodes to the root node (incidentally called xml).

These are the basics, you can create and append a node in just a line (13th, for example), you can do a lot of other things with the dom api. It is up to you.

<?php    
	/* create a dom document with encoding utf8 */
	$domtree = new DOMDocument('1.0', 'UTF-8');

	/* create the root element of the xml tree */
	$xmlRoot = $domtree->createElement("xml");
	/* append it to the document created */
	$xmlRoot = $domtree->appendChild($xmlRoot);



	/* you should enclose the following lines in a cicle */
	$currentTrack = $domtree->createElement("track");
	$currentTrack = $xmlRoot->appendChild($currentTrack);
    $currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
	$currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));

	$currentTrack = $domtree->createElement("track");
	$currentTrack = $xmlRoot->appendChild($currentTrack);
    $currentTrack->appendChild($domtree->createElement('path','song2.mp3'));
	$currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));

	/* get the xml printed */
	echo $domtree->saveXML();
?>

Edit: Just one other hint: The main advantage of using an xmldocument (the dom document one or the simplexml one) instead of printing the xml,is that the xmltree is searchable with xpath query

See also original question in stackoverflow

#64: Are SVG parameters such as 'xmlns' and 'version' needed? (Score: 239)

Created: 2013-08-27 Last updated: 2019-01-17

Tags: xml, svg, tags

In about half of the svg examples I see on the internet, the code is wrapped in plain simple <svg></svg> tags.

In the other half, the svg tags have lots of complicated attributes like this:

<svg 
  xmlns="http://www.w3.org/2000/svg" 
  version="1.1" 
  xmlns:xlink="http://www.w3.org/1999/xlink"> 

My question is: is it ok to use the simple svg tags? I’ve tried playing around with the complicated ones, and everything works fine at my end if I don’t include them.

#64 Best answer 1 of Are SVG parameters such as 'xmlns' and 'version' needed? (Score: 254)

Created: 2015-12-13 Last updated: 2018-09-26

The xmlns="http://www.w3.org/2000/svg" attribute is:

  • Required for image/svg+xml files. 1
  • Optional for inlined <svg>. 2

The xmlns:xlink="http://www.w3.org/1999/xlink" attribute is:

  • Required for image/svg+xml files with xlink: attributes. 1
  • Optional for inlined <svg> with xlink: attributes. 2

The version="1.1" attribute is:

  • Recommended to comply with image/svg+xml files standards. 3
  • Apparently ignored by every user agent. 4
  • Removed in SVG 2. 5

1 Internationalized Resource Identifiers (RFC3987)
2 Since HTML5
3 Extensible Markup Language (XML) 1.0
4 Probably until the release of further major versions.
5 SVG 2, W3C Candidate Recommendation, 07 August 2018

#64 Best answer 2 of Are SVG parameters such as 'xmlns' and 'version' needed?(Score: 242)

Created: 2013-08-27 Last updated: 2018-09-26

All user agents (browsers) ignore the version attribute, so you can always drop that.

If you embed your SVG inline in a HTML page and serve that page as text/html then xmlns attributes are not required. Embedding SVG inline in HTML documents is a fairly recent innovation that came along as part of HTML5.

If however you serve your page as image/svg+xml or application/xhtml+xml or any other MIME type that causes the user agent to use an XML parser then the xmlns attributes are required. This was the only way to do things until recently so there is a lot of content served like this.

See also original question in stackoverflow

#65: How to escape "&" in XML? (Score: 237)

Created: 2012-09-21 Last updated: 2020-01-31

Tags: xml

I write

 <string name="magazine">Newspaper & Magazines</string>

in strings.xml

But the Compiler says:

The entity name must immediately follow the '&' in the entity reference.	strings.xml	/OOReaderWidget/res/values	line 9	Android XML Format Problem

So how Can I show a “&” in strings.xml? Thanks!

#65 Best answer 1 of How to escape "&" in XML? (Score: 455)

Created: 2012-09-21

use &amp; in place of &

change to

<string name="magazine">Newspaper &amp; Magazines</string>

#65 Best answer 2 of How to escape "&" in XML?(Score: 78)

Created: 2012-09-21 Last updated: 2017-01-17

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

See also original question in stackoverflow

#66: How to change line color in EditText (Score: 235)

Created: 2014-07-10 Last updated: 2014-07-10

Tags: android, xml, layout, styles

I am creating an EditText in my layout xml file

But I want to change color line in EditText from Holo to (for example) red. How that can be done?

enter image description here

#66 Best answer 1 of How to change line color in EditText (Score: 345)

Created: 2014-07-10 Last updated: 2020-08-10

This is the best tool that you can use for all views and its FREE many thanks to @Jérôme Van Der Linden.

The Android Holo Colors Generator allows you to easily create Android components such as EditText or spinner with your own colours for your Android application. It will generate all necessary nine patch assets plus associated XML drawable and styles which you can copy straight into your project.

http://android-holo-colors.com/

UPDATE 1

This domain seems expired but the project is an open source you can find here

https://github.com/jeromevdl/android-holo-colors

try it

this image put in the background of EditText

android:background="@drawable/textfield_activated"

enter image description here


UPDATE 2

For API 21 or higher, you can use android:backgroundTint

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Underline color change"
        android:backgroundTint="@android:color/holo_red_light" />

Update 3 Now We have with back support AppCompatEditText

Note: We need to use app:backgroundTint instead of android:backgroundTint

<android.support.v7.widget.AppCompatEditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:hint="Underline color change"
    app:backgroundTint="@color/blue_gray_light" />

Update 4 AndroidX version

  <androidx.appcompat.widget.AppCompatEditText

    app:backgroundTint="@color/blue_gray_light" />

#66 Best answer 2 of How to change line color in EditText(Score: 214)

Created: 2017-01-24 Last updated: 2020-03-29

I don’t like previous answers. The best solution is to use:

<android.support.v7.widget.AppCompatEditText
     
      app:backgroundTint="@color/blue_gray_light" />

android:backgroundTint for EditText works only on API21+ . Because of it, we have to use the support library and AppCompatEditText.

Note: we have to use app:backgroundTint instead of android:backgroundTint

AndroidX version

<androidx.appcompat.widget.AppCompatEditText

      app:backgroundTint="@color/blue_gray_light" />



See also [original question in stackoverflow](https://stackoverflow.com/questions/24677414/how-to-change-line-color-in-edittext)

## #67: How to use XPath in Python? (Score: 232)

*Created: 2008-08-12 Last updated: 2020-07-10*

*Tags: python, xml, dom, xpath, python-2.x*

What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website?

### #67 Best answer 1 of How to use XPath in Python? (Score: 130)

*Created: 2008-08-26 Last updated: 2016-02-07*

[libxml2](http://xmlsoft.org/python.html) has a number of advantages:

1. Compliance to the [spec](http://www.w3.org/TR/xpath)
2. Active development and a community participation 
3. Speed. This is really a python wrapper around a C implementation. 
4. Ubiquity. The libxml2 library is pervasive and thus well tested.

Downsides include:

1. Compliance to the [spec](http://www.w3.org/TR/xpath). It's strict. Things like default namespace handling are easier in other libraries.
2. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.
3. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.

If you are doing simple path selection, stick with [ElementTree](http://effbot.org/zone/element-xpath.htm) ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.


**Sample of libxml2 XPath Use**
***
<pre><code>import libxml2

doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
    print "xpath query: wrong node set size"
    sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
    print "xpath query: wrong node set value"
    sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
</code></pre>

**Sample of ElementTree XPath Use**
***
<pre><code>from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
	print e.get('title').text</code></pre>
 
***




### #67 Best answer 2 of How to use XPath in Python?(Score: 85)

*Created: 2008-08-12 Last updated: 2013-01-10*

The [lxml package][1] supports xpath.  It seems to work pretty well, although I've had some trouble with the self:: axis.  There's also [Amara][2], but I haven't used it personally.


  [1]: http://lxml.de/
  [2]: http://pypi.python.org/pypi/Amara/1.1.6


See also [original question in stackoverflow](https://stackoverflow.com/questions/8692/how-to-use-xpath-in-python)

## #68: google protocol buffers vs json vs XML (Score: 230)

*Created: 2012-12-25 Last updated: 2015-05-14*

*Tags: xml, json, protocol-buffers, data-serialization*

I would like to know the merits & de-merits of

- Google Protocol Buffers
- JSON
- XML

I want to implement one common framework for two application, one in Perl and second in Java. So, would like to create common service which can be used by both technology i.e. Perl & Java.

Both are web-applications.

Please share me your valuable thoughts & suggestion on this. I have seen many links on google but all have mixed opinions.

### #68 Best answer  of google protocol buffers vs json vs XML (Score: 283)

*Created: 2012-12-25*

Json

- human readable/editable
- can be parsed without knowing schema in advance
- excellent browser support
- less verbose than XML

XML

- human readable/editable
- can be parsed without knowing schema in advance
- standard for SOAP etc
- good tooling support (xsd, xslt, sax, dom, etc)
- pretty verbose

Protobuf

- very dense data (small output)
- hard to robustly decode without knowing the schema (data format is internally ambiguous, and needs schema to clarify)
- very fast processing
- not intended for human eyes (dense binary)

All have good support on most platforms.

Personally, I rarely use XML these days. If the consumer is a browser or a public API I tend to use json. For internal APIs I tend to use protobuf for performance. Offering both on public API (either via headers, or separate endpoints) works well too.



See also [original question in stackoverflow](https://stackoverflow.com/questions/14028293/google-protocol-buffers-vs-json-vs-xml)

## #69: XPath to select element based on childs child value (Score: 229)

*Created: 2012-03-13*

*Tags: xml, xpath*

Trying to select an element based on the value of one of it's childrens childrens

Thinking the following but not working, appreciate any help, thanks

`./book[/author/name = 'John']` or

    ./book[/author/name text() = 'John']

Want all books where the author name = 'John'

Xml file

    <list>
       <book>
          <author>
             <name>John</name>
             <number>4324234</number>
          </author>
          <title>New Book</title>
          <isbn>dsdaassda</isbn>
       </book>
       <book>...</book>
       <book>...</book>
    </list>



### #69 Best answer  of XPath to select element based on childs child value (Score: 327)

*Created: 2012-03-13*

Almost there. In your predicate, you want a *relative* path, so change 

    ./book[/author/name = 'John'] 

to either

    ./book[author/name = 'John'] 

or

    ./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an `author`.





See also [original question in stackoverflow](https://stackoverflow.com/questions/9683054/xpath-to-select-element-based-on-childs-child-value)

## #70: XML Schema minOccurs / maxOccurs default values (Score: 227)

*Created: 2011-01-27 Last updated: 2011-01-28*

*Tags: xml, xsd*

I'm wondering how the XML Schema specification handles these cases:

    <xsd:element minOccurs="1" name="asdf"/>
No maxOccurs given -> Is this the cardinality [1..1]?

    <xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>

I suppose this is simply invalid?

    <xsd:element maxOccurs="2" name="asdf"/>

Is this the cardinality [0..2] or [1..2]?

Is there an "official" definition on how the XML Schema spec handles these cases?

### #70 Best answer 1 of XML Schema minOccurs / maxOccurs default values (Score: 338)

*Created: 2011-01-27 Last updated: 2012-12-09*

The default values for `minOccurs` and `maxOccurs` are 1. Thus:

    <xsd:element minOccurs="1" name="asdf"/>

cardinality is [1-1] Note: if you specify *only* minOccurs attribute, it can't be greater than 1, because the default value for maxOccurs is 1.

    <xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>

invalid

    <xsd:element maxOccurs="2" name="asdf"/>

cardinality is [1-2] Note: if you specify *only* maxOccurs attribute, it can't be smaller than 1, because the default value for minOccurs is 1.

    <xsd:element minOccurs="0" maxOccurs="0"/>

is a valid combination which makes the element prohibited.

For more info see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints


### #70 Best answer 2 of XML Schema minOccurs / maxOccurs default values(Score: 76)

*Created: 2015-11-13 Last updated: 2016-05-19*

<sub>*New, expanded answer to an old, commonly asked question...*</sub>

Default Values
--------------

 - Occurrence constraints `minOccurs` and `maxOccurs` **default to `1`**.


----------

Common Cases Explained
----------------------

    <xsd:element name="A"/>

means `A` is ***required*** and must appear ***exactly once***.

----------

    <xsd:element name="A" minOccurs="0"/>

means `A` is ***optional*** and may appear ***at most once***.

----------

     <xsd:element name="A" maxOccurs="unbounded"/>

means `A` is ***required*** and may repeat an ***unlimited number of times***.

----------

     <xsd:element name="A" minOccurs="0" maxOccurs="unbounded"/>

means `A` is ***optional*** and may repeat an ***unlimited number of times***.

----------

See Also
----------

 - [W3C XML Schema Part 0: Primer][1]

   > In general, an element is required to appear when the value of
   > minOccurs is 1 or more. The maximum number of times an element may
   > appear is determined by the value of a maxOccurs attribute in its
   > declaration. This value may be a positive integer such as 41, or the
   > term unbounded to indicate there is no maximum number of occurrences.
   > The default value for both the minOccurs and the maxOccurs attributes
   > is 1. Thus, when an element such as comment is declared without a
   > maxOccurs attribute, the element may not occur more than once. Be sure
   > that if you specify a value for only the minOccurs attribute, it is
   > less than or equal to the default value of maxOccurs, i.e. it is 0 or 1.
   > Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs,
   > i.e. 1 or more. If both attributes are omitted, the element must
   > appear exactly once.

 - [W3C XML Schema Part 1: Structures Second Edition][2] 

        <element
          maxOccurs = (nonNegativeInteger | unbounded)  : 1
          minOccurs = nonNegativeInteger : 1
          >

        </element>


  [1]: http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints
  [2]: http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#element-element



See also [original question in stackoverflow](https://stackoverflow.com/questions/4821477/xml-schema-minoccurs-maxoccurs-default-values)


<hr/>
<small>
Notes:

1. This page use API to get the relevant data from stackoverflow community.
2. Content license on this page is *CC BY-SA 3.0*.
3. `score` = `up votes` - `down votes`.
</small>