[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Return XML array element number in Xpath

Posted on 2011-09-21
5
Medium Priority
?
1,114 Views
Last Modified: 2013-11-11
I have the following XML:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ns2:findAllRolesResponse xmlns:ns2="http://x.xx.xxx.com/" xmlns:ns3="http://x.xx.xx.com/">
      <return>
        <description>HOUSEMAN</description>      
      </return>
      <return>
        <description>AM HOUSEKEEPER</description>    
      </return>    
      <return>
        <description>CLERK</description>    
      </return>      
    </ns2:findAllRolesResponse>
  </soap:Body>
</soap:Envelope>

When the attached code - recursive method called ProcessNodes - runs it produces the xpath without the array number:
     
-----------------------------
row: 2
name:      description
xpath1:      /soap:Envelope/soap:Body/ns2:findAllRolesResponse/return/description
value1:      HOUSEMAN
   
-----------------------------
row: 4
name:      description
xpath1:      /soap:Envelope/soap:Body/ns2:findAllRolesResponse/return/description
value1:      AM HOUSEKEEPER
   
-----------------------------
row: 6
name:      description
xpath1:      /soap:Envelope/soap:Body/ns2:findAllRolesResponse/return/description
value1:      CLERK
-----------------------------

What I would like is the xpath array element number added to the xpath.  So, for example:

name:      description
xpath1:      /soap:Envelope/soap:Body/ns2:findAllRolesResponse/return[1]/description
value1:      HOUSEMAN

name:      description
xpath1:      /soap:Envelope/soap:Body/ns2:findAllRolesResponse/return[2]/description
value1:      AM HOUSEKEEPER


Any ideas?

Thanks in advance.

private void LoadXmlToGrid()
        {
            //load xml, get xpath value pairs, bind to gridview            
            try
            {
                m_XmlDoc.Load(m_XmlFileName);

                DataTable myDataTable = new DataTable();

                myDataTable.Columns.Add("name");
                myDataTable.Columns.Add("xpath1");
                myDataTable.Columns.Add("value1");

                //set node path to start the xpath query build
                XmlNode XpathNodes = m_XmlDoc.SelectSingleNode("/*[local-name(.)='Envelope'][1]/*[local-name(.)='Body'][1]/*[local-name(.)='findAllRolesResponse']");
                                
                //get xpath value pair; save to datatable
                ProcessNode(XpathNodes, myDataTable);

                //bind to datagrid view
                //dgXpath.AutoGenerateColumns = false;
                dgXpath.DataSource = myDataTable;
              
            }

        //recursive method to read xml file to get xpath value pair
        private void ProcessNode(XmlNode node, DataTable table)
        {
            try
            {
                StringBuilder xpath = new StringBuilder();
                XmlNode temp = node;
                XmlNodeList children = node.SelectNodes("*");
                
                while (temp.ParentNode != null && temp.Name != "#document")
                {
                    xpath.Insert(0, "/" + temp.Name);
                    temp = temp.ParentNode;                   
                }

                string value = children.Count > 0 ? string.Empty : node.InnerText;

                table.Rows.Add(new object[] { node.Name, xpath.ToString(), value });

               
                foreach (XmlNode child in children)
                {
                   
                    if (child.NodeType == XmlNodeType.Element)
                    {
                        ProcessNode(child, table);                     
                    }
                }
                
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }

Open in new window

0
Comment
Question by:j420exe1
  • 3
  • 2
5 Comments
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 36578946
Well, if you're only interested in 'description' nodes, and there's only ever 1 in a 'return' node, then an easy way would be to use a global variable and append the index yourself when prefixing your stringbuilder with the current node name:

        private int m_Counter = 0;

        private void ProcessNode(XmlNode node, DataTable table)
        {
            try
            {
                StringBuilder xpath = new StringBuilder();
                XmlNode temp = node;
                XmlNodeList children = node.SelectNodes("*");
                
                while (temp.ParentNode != null && temp.Name != "#document")
                {
                    if (node.Name == "description" && temp.Name == "return") {
                        ++m_Counter;
                        xpath.Insert(0, "]").Insert(0, m_Counter.ToString()).Insert(0, "[");
                    }
                    xpath.Insert(0, "/" + temp.Name);
                    temp = temp.ParentNode;                   
                }
...

Open in new window

0
 

Author Comment

by:j420exe1
ID: 36579516
No, the XML could contain 1 to many elements and nested elements.  The goal is to crawl the XML and return the xpath value pair so the code needs to be dynamic enough to handle all variations of the xml soap message.
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 36580157
ah, well to do it properly I think we should add an xsd schema to the xml, but it just might be possible without that.

Would it be terribly inconvenient if any single occurrences would have a [1] after the name?
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 2000 total points
ID: 36580220
ah, forget that last remark, I built in another check.

        private void ProcessNode(XmlNode node, DataTable table, StringBuilder xpath)
        {
            try
            {
                if (xpath == null)
                    xpath = new StringBuilder();

                xpath.Append("/" + node.Name);

                int cnt = 1;
                XmlNode tmptmp = node;
                do {
                    tmptmp = tmptmp.PreviousSibling;
                    if (tmptmp != null && tmptmp.Name == node.Name)
                        cnt++;
                } while (tmptmp != null);
                if (cnt == 1) {
                    tmptmp = node;
                    bool fnd = false;
                    do {
                        tmptmp = tmptmp.NextSibling;
                        if (tmptmp!= null && tmptmp.Name == node.Name) {
                            fnd = true;
                            break;
                        }
                    } while (tmptmp != null);
                    if (!fnd)
                        cnt = 0;
                }
                if (cnt != 0)
                    xpath.Append("[").Append(cnt.ToString()).Append("]");

                XmlNodeList children = node.SelectNodes("*");
                string value = children.Count > 0 ? string.Empty : node.InnerText;

                table.Rows.Add(new object[] { node.Name, xpath.ToString(), value });

               
                string bak = xpath.ToString();
                foreach (XmlNode child in children)
                {
                    StringBuilder xpath2 = new StringBuilder(bak);
                    if (child.NodeType == XmlNodeType.Element)
                    {
                        ProcessNode(child, table, xpath2);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }

Open in new window

0
 

Author Closing Comment

by:j420exe1
ID: 36580902
Awesome!  Thanks!
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Create a Windows 10 custom Image with custom task bar and custom start menu using XML for deployment.
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses
Course of the Month18 days, 23 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question