1

I'm using Python and lxml. My xml file:

<Example>
    <Path>
        <Some.Node>
            // ...
        </Some.Node>
        <Some.Node>
            <Known.Node KnownAttribute="123"/>
            <Some.Stuff>
                <Nothing.Important>Bla</Nothing.Important>
            </Some.Stuff>
            <Relevant.Node>
                <Property>
                    <Name>Some</Name>
                    <Value>True</Value>
                </Property>
                <Property>
                    <Name>Known.Name</Name>
                    <Value>Desired Value</Value>
                </Property>
                <Property>
                    <Name>Some.Other</Name>
                    <Value>Yes</Value>
                </Property>
                // ...
            </Relevant.Node>
            // ...
        </Some.Node>
        <Some.Node>
            // ...
        </Some.Node>
    </Path>
</Example>

There are multiple <Some.Node> nodes and I'm only interested in the one with KnownAttribute equal to 123. This part I got:

query = "//Known.Node[@KnownAttribute='%s']" % attribute_value

However, I need to get the value of <Relevant.Node>/<Property>/<Value> where <Name> has value Known.Name.

This was my best try but it didn't work:

root = etree.parse(xml_file).getroot()
query = "//Known.Node[@KnownAttribute='%s']/..//Property[Name='Known.Name']/Value" % attribute_value
result = root.xpath(query)
print(result[0].text)

It should print, of course, Desired Value but it just returns empty value/whitespace.

How can I get the value I need?

0

1 Answer 1

2

You are really close. You can ask for the text of the node in the xpath expression.

query = "//Known.Node[@KnownAttribute='%s']/..//" % attribute_value
query += "Property[Name='Known.Name']/Value/text()" 
result = root.xpath(query)
print(result[0])
# prints:
Desired Value
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.