Solved

xpath

Posted on 2004-09-24
6
761 Views
Last Modified: 2012-08-13
Hi
i developed small application using asp.net,c# which gets the nodelist, from nodelist will get the data based on elementname.Here is the code  :
here Utility is my own xml class it returns xmlnodelist.
XmlNodeList mappingnodelist=Utility.GetNodeList("/root/Summary",mapping);
string d1=datanode.SelectSingleNode("FirstName").InnerText
string d2=datanode.SelectSingleNode("LastName").InnerText
string d3=datanode.SelectSingleNode("City").InnerText

XML structure :
<root></root>
<Summary>
<FirstName></FirstName>
<lastName></lastName>
<City></City>
</Summary>
<Summary>
<FirstName></FirstName>
<lastName></lastName>
<City></City>
</Summary>

<Summary>
<FirstName></FirstName>
<lastName></lastName>
<City></City>
</Summary>

</root>
i am able to get the data bsed on element name.

Now i want to develop same implementation using xpathdocument,xpathnodeiterator or any method.
Basi reason behind that we can sort with xpathnavigator,xpathexpression.
using xpathdocument i am able to get the xpathnodeiterator.after that i am not sure how to get the value of particular element.it seems always we need to use movenext and it is forward only.

If anybody have clue pls help me.

Note : basi reason i want to sort the xmldocumet(XMLDocument or xpathdocument or xpathdatadocument).
0
Comment
Question by:pprasadravi
  • 2
6 Comments
 
LVL 26

Accepted Solution

by:
rdcpro earned 250 total points
ID: 12148265
If you simply want to sort the nodelist, based on some value you can get out of each node, you use IComparable to sort.  Here's an example from another question I answered.  It's untested, and does not exactly do what you want, but then I don't know what criteria you want to sort on.


public class NodeComparer : IComparer  
{

int IComparer.Compare( Object x, Object y )  
{
    XmlElement xNode = (XmlElement)x;
    XmlElement yNode = (XmlElement)y;

    // Right here you do a test, and compare the nodes using whatever criteria you need to determine which one comes first.
    // This example isn't quite correct, since we really want to compare ints, and GetAttribute returns a string.  
    // Convert to an int, then compare.  In your case, probably get the child nodes you want to sort on, and compare.
    // IComparer returns one of three things depending on how the two objects compare:
    // Less than zero x is less than y.
    // Zero x equals y.
    // Greater than zero x is greater than y.
    // So if you override it, you have to provide a series of tests on your objects that ultimately return -1, 0 or 1.
    if (xNode.GetAttribute("Left") < yNode.GetAttribute("Left")) return -1;
    if (xNode.GetAttribute("Left") > yNode.GetAttribute("Left")) return 1;
    return 0
}

}


Then in your code after you get the nodelist:


// Instance of my NodeComparer to sort
NodeComparer myNodelistOrder = new NodeComparer();

// Create an arraylist or enum of your nodelist
IEnumNodes = myNodeList.GetEnumerator();

IEnumNodes.Sort(myNodelistOrder, NodeComparer );


Regards,
Mike Sharp
0
 

Author Comment

by:pprasadravi
ID: 12150799
Hi Mike
You are right.
 
This is my first implementation using xpath.The way i am thinking may be wrong.Pls update me.

Here is my problem how to get the elemet values(Ex: city,firstname and last name).If i know the elemt name can i get the value directly without loopning the list.Here is my Example :
Persons is root node.Header is singlenode.Person may repeat number of times.

My Implementation :

first i want to get header information .next i am want to get all  Person nodes.When i have person node i want to get first city,Firstname and Lastname .

i use to use selectsinglenode to get the particular element value.But i am not sure what i need to use it with xpathnodeiterator.


<Persons>
    <Header>
       <HeaderName></HeaderName>
       <HeaderInfo></HeaderInfo>
        <HeaderText></HeaderText>
     </Header>
    <Person>
          <FirstName></FirstName>
          <LastName></LastName>
           <City></City>
     </Person>
     <Person>
          <FirstName></FirstName>
          <LastName></LastName>
           <City></City>
     </Person>

     <Person>
          <FirstName></FirstName>
          <LastName></LastName>
           <City></City>
     </Person>


</Persons>

Thanks
Ravi
0
 
LVL 6

Assisted Solution

by:Praesidium
Praesidium earned 250 total points
ID: 12153917
I think you can still use select single node... what if you did it something like:

private void Refresh() {
                  //Load Xml document
                  XmlDocument xmldocument = new XmlDocument();
                  xmldocument.Load("your xml document");
                                                                  
                                                try {
                        xmldocument.Load(url);
                              
                        // store in cache, (NotRemovable) for failover measure.
                        this.Cache.Insert("LastXMLDoc", xmldocument, null,
                              System.Web.Caching.Cache.NoAbsoluteExpiration,
                              System.Web.Caching.Cache.NoSlidingExpiration,
                              System.Web.Caching.CacheItemPriority.NotRemovable,
                              null
                        );
                  } catch(Exception) {
                        // failover from last good cached quote
                        try {
                              nybotdoc = (XmlDocument)this.Cache["LastXMLDoc"];
                        } catch(Exception) {
                              // not retrievable.
                              // give a nice error message in some literal
                              return;
                        }
                  }

                  this.nsmanager = new XmlNamespaceManager(xmldocument.NameTable);
                  this.nsmanager.AddNamespace("ns2", "http://"); // if you have any namespaces you will want to use a nsm                  
                  this.nsmanager.AddNamespace("ns1", "http://");
                  
                  this.XMLDocument.DataSource = xmldocument.SelectNodes("/persons/person", nsmanager);
                  this.XMLDOCUMENT.DataBind();

            }

            private void XMLDOCMENT_ItemDataBound(object sender, RepeaterItemEventArgs e) {
                  if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
                        XmlNode item = (XmlNode)e.Item.DataItem;
                        
                        Trace.Warn(item.InnerXml);
                        
                        firstName.Text = item.SelectSingleNode("FirstName", this.nsmanager).InnerText;
                        lastName.Text = item.SelectSingleNode("LastName", this.nsmanager).InnerText;
                        city.Text = item.SelectSingleNode("City", this.nsmanager).InnerText;
                  }
            }

where all the strings exist, and get bound to literals or something of that nature!
0
 
LVL 6

Expert Comment

by:Praesidium
ID: 12153918
then you just throw the literals into a repeater, and let it go to town!
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
What XAML would produce this? 3 79
Vb.net XML Read all nodes and 4 84
How to read XML file attributes... 17 59
Convert XML to excel12book 5 29
Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

776 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