• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1004
  • Last Modified:

Simple 'get elements by name' XPath question (in C#)

Perphaps someone can explain to me why I do not find what I expect with XPath in an XmlDocument. I have an XmlNode (called xml). If I run xml.OuterXml I get the following:

<MirrorAttributeChangeResponse xmlns="company/ws/shared/attribute">
  <MirrorAttributeChangeResult>
    <AttributeChange>
      <FieldName>coloredfield</FieldName>
      <AttributeName>style</AttributeName>
      <AttributeValue>;background-color: red</AttributeValue>
      <Overwrite>false</Overwrite>
    </AttributeChange>
    <AttributeChange>
      <FieldName>coloredfield</FieldName>
      <AttributeName>style</AttributeName>
      <AttributeValue>;background-color: red</AttributeValue>
      <Overwrite>false</Overwrite>
    </AttributeChange>
    <AttributeChange>
      <FieldName>coloredfield</FieldName>
      <AttributeName>style</AttributeName>
      <AttributeValue>;background-color: red</AttributeValue>
      <Overwrite>false</Overwrite>
    </AttributeChange>
  </MirrorAttributeChangeResult>
</MirrorAttributeChangeResponse>

If I run xml.SelectNodes("//AttributeChange") I expect to get the 3 AttributeChange nodes, but I get 0 nodes. Why? Does it have something to do with namespaces?
0
gyxi
Asked:
gyxi
  • 2
1 Solution
 
Geert BormansInformation ArchitectCommented:
yes, the namespace prevents the XPath from seeing the three nodes
you don't need AttributeChange, but  {company/ws/shared/attribute}:AttributeChange (that is a pseudo notation)

there are two options
- you add a namespacemanager to the query
- or you go for the localname()

xml.SelectNodes("//*[local-name() = 'AttributeChange']")
will give you what you need
0
 
gyxiAuthor Commented:
Thanks Gertone, that solved it. I hope it still performs about the same. It looks kind of expensive.
0
 
Geert BormansInformation ArchitectCommented:
welcomr,

it IS expensive, hopefully your XML is not too big
If it is too expensive in your program, use a namespace manager
http://www.timrayburn.net/default,date,2005-01-15.aspx
(scroll down the page to actually get the namespace black belt article of 15-jan
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now