How to print a specific xml value using python?
Question: I have the xml which looks like below

    
    
    <api>
    <apicat>
        <cat>
            <id>1</id>
            <name>testname</name>
        </cat>
        <cat>
            <id>2</id>
            <name>testname2</name>
        </cat>
        <cat>
            <id>3</id>
            <name>testname3</name>
        </cat>
    </apicat>
    

How to print the name which has id=2? And also please note that if the xml is
not bringing back values in the same order and also if the number of results
is higher 10,000?


Answer: You can do this easily with [lxml](/questions/tagged/lxml "show questions
tagged 'lxml'") module with a [xpath](/questions/tagged/xpath "show questions
tagged 'xpath'") expression :

    
    
    from lxml import etree
    
    file = "file://path/to/file.xml"
    doc = etree.parse(file)
    
    print doc.xpath('//cat[id=2]/name/text()')[0]
    

See <http://lxml.de/>

and a [Xpath tutorial](http://www.w3schools.com/xpath/default.asp)

Your XML file is not valid, this one should be :

    
    
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <api>
        <apicat>
            <cat>
                <id>1</id>
                <name>testname</name>
            </cat>
            <cat>
                <id>2</id>
                <name>testname2</name>
            </cat>
            <cat>
                <id>3</id>
                <name>testname3</name>
            </cat>
        </apicat>
    </api>
    

