We help IT Professionals succeed at work.

Getting Values From XmlNode

DuNuNuBatman
DuNuNuBatman asked
on
1,589 Views
Last Modified: 2008-01-09
I'm trying to get certain values from this xml statement, but I keep running into problems. What I'm trying to do is get the ows_Title value, the ows_Description value and the ows_Status value.
There should only be one row returned, but how do I loop through multiple rows and get their values?

The results I have to work with are a XmlNode type.

<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema" xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <rs:data ItemCount="1">
        <z:row ows_Title="Pattie Laptop " ows_Description="Configure and get Pattie the better laptop" ows_Status="Closed" ows_MetaInfo="23;#" ows__ModerationStatus="0" ows__Level="1" ows_ID="23" ows_owshiddenversion="4" ows_UniqueId="23;#{F8721921-52A6-49F0-837F-70E9B7067D9C}" ows_FSObjType="23;#0" ows_Created="2007-09-04T22:17:23Z" ows_FileRef="23;#clients/ada_es/servicerequests/Lists/Service Requests/23_.000" />
    </rs:data>
</listitems>
Comment
Watch Question

CERTIFIED EXPERT

Commented:

Dim xtr As XmlTextReader

  xtr = New XmlTextReader("your xml file path")

  xtr.WhiteSpaceHandling = WhiteSpaceHandling.NONE
 
  xtr.Read()

 xtr.Read()

  While Not xtr.EOF
    xtr.Read()
    If Not xtr.IsStartElement() Then
      Exit While
    End If
    'Get the Gender Attribute Value
    Dim title as string = xtr.GetAttribute("ows_Title")
End While
  ''close the reader
  xtr.Close()
CERTIFIED EXPERT

Commented:
another way to read the attributes is
Dim xmldoc As New Xml.XmlDocument
        Dim xmlnlist As Xml.XmlNodeList
        Dim xmln As Xml.XmlNode

        Try
         
            xmldoc.Load("your xml file path")
            xmlnlist = xmldoc.SelectNodes("//z:row")

            For Each xmln In xmlnlist
                Dim title As String= xmln.Attributes("ows_Title").Value
Dim description As String= xmln.Attributes("ows_Description").Value


            Next
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

I'm confused. There should be one row returned, or you need to loop through multiple rows?
Your example shows just one row.
If you know that the Xml Document's Document Element will have one rs:data node then the following code will loop through the z:row nodes.
Note that the XmlDoc object is the Xml Document with the Xml loaded up.
foreach(System.Xml.XmlNode tmpNode in XmlDoc.DocumentElement.FirstChild)
      {
        string Title = tmpNode.Attributes.GetNamedItem("ows_Title").Value;        
      }
CERTIFIED EXPERT

Commented:
I think he means multiple attributes and not multiple rows

Author

Commented:
No, I meant multiple rows. In this example I only need to get the results of one row. But I needed to know how to get the results of multiple rows. I used your second example because it appears to work for both uses.

I get this error when running your example however. This part is throwing it.
xmlnlist = xmldoc.SelectNodes("//z:row")


System.Xml.XPath.XPathException was unhandled by user code
  Message="Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function."
  Source="System.Xml"
  StackTrace:
       at MS.Internal.Xml.XPath.CompiledXpathExpr.get_QueryTree()
       at System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr, XPathNodeIterator context)
       at System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr)
       at System.Xml.XPath.XPathNavigator.Select(XPathExpression expr)
       at System.Xml.XPath.XPathNavigator.Select(String xpath)
       at System.Xml.XmlNode.SelectNodes(String xpath)
       at ADADashboard.RequestStatus.GetRequestStatus() in C:\Users\Josh\Desktop\Dashboard\RequestStatus.aspx.cs:line 79
       at ADADashboard.RequestStatus.Page_Load(Object sender, EventArgs e) in C:\Users\Josh\Desktop\Dashboard\RequestStatus.aspx.cs:line 27
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:
Multiple rows but always just one data node?
Then this should do it
foreach(System.Xml.XmlNode tmpNode in XmlDoc.DocumentElement.FirstChild)
      {
        string Title = tmpNode.Attributes.GetNamedItem("ows_Title").Value;        
      }
CERTIFIED EXPERT

Commented:
my second example will aloow you to get the results for multiple rows and then loop through them
CERTIFIED EXPERT

Commented:
the error is because of a z: prefix

Author

Commented:
How do I fix that?
CERTIFIED EXPERT

Commented:
try this:
Dim xmldoc As New Xml.XmlDocument
        Dim xmlnlist As Xml.XmlNodeList
        Dim xmln As Xml.XmlNode

        Try
             Dim nsmgr as XmlNamespaceManager = new XmlNamespaceManager(xmldoc.NameTable)
          nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform")
            xmldoc.Load("your xml file path")
            xmlnlist = xmldoc.SelectNodes("//z:row")

            For Each xmln In xmlnlist
                Dim title As String= xmln.Attributes("ows_Title").Value
            Dim description As String= xmln.Attributes("ows_Description").Value
            Next
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try





Author

Commented:
Here is what I have so far. One of the problem is the results I get from the web service I am calling return a XmlNode type. So I never actually need to create a XmlDoc to add the Node to it.

Lists listService = new Lists();
            listService.Credentials = new System.Net.NetworkCredential(spUsername, spPassword, spDomain);
            listService.Url = ConfigSettings.SPListUrl;


            // List settings
            string listName = ConfigSettings.SPListGuid;
            string viewName = null;
            string rowLimit = null;
            string webID = null;

            XmlDocument xmlDoc = new XmlDocument();

            // List Query Caml
            XmlNode listQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            listQuery.InnerXml = "<Where>" +
                                    "<Eq>" +
                                        "<FieldRef Name='ID' />" +
                                        "<Value Type='Number'>" + _ServiceRequestID + "</Value>" +
                                    "</Eq>" +
                                 "</Where>";

            // List View Caml
            XmlNode listViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
            listViewFields.InnerXml = "<FieldRef Name='Title' />" +
                                      "<FieldRef Name='Description' />" +
                                      "<FieldRef Name='Status' />" +
                                      "<FieldRef Name='Resolution' />";

            // List Query Options Caml
            XmlNode listQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
            listQueryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" +
                                        "<DateInUtc>TRUE</DateInUtc>";

            XmlNode results = listService.GetListItems(listName, viewName, listQuery, listViewFields, rowLimit, listQueryOptions, webID);
           
            XmlNodeList nodeList = results.SelectNodes("//z:row");

            foreach (XmlNode node in nodeList)
            {
                Response.Write(node.Attributes["ows_Title"].InnerText);
                Response.Write(node.Attributes["ows_Description"].InnerText);
                Response.Write(node.Attributes["ows_Status"].InnerText);
            }
            Response.Write("<br />");
            Response.Write(Server.HtmlEncode(results.OuterXml));
CERTIFIED EXPERT

Commented:
here is just what you need:

http://blogs.msdn.com/mjeelani/default.aspx

Author

Commented:
which one am I looking for?
CERTIFIED EXPERT

Commented:
this will work:

Dim xmldoc As New Xml.XmlDocument
        Dim xmlnlist As Xml.XmlNodeList
        Dim xmln As Xml.XmlNode

        Try
            xmldoc.Load("your xml file path")
            'Since the XML returned by SPS contains namespace prefixes - we need to create a XmlNamespaceManager
            Dim ListItemsNamespacePrefix As String = "z"
            Dim ListItemsNamespaceURI As String = "#RowsetSchema"

            Dim PictureLibrariesNamespacePrefix As String = "s"
            Dim PictureLibrariesNamespaceURI As String = "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"

            Dim WebPartsNamespacePrefix As String = "dt"
            Dim WebPartsNamespaceURI As String = "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"

            Dim DirectoryNamespacePrefix As String = "rs"
            Dim DirectoryNamespaceURI As String = "urn:schemas-microsoft-com:rowset"

            'now associate with the xmlns namespaces (part of all XML nodes returned
            'from SharePoint) a namespace prefix which we can then use in the queries
            Dim nsmgr As Xml.XmlNamespaceManager = New Xml.XmlNamespaceManager(xmldoc.NameTable)

            nsmgr.AddNamespace(ListItemsNamespacePrefix, ListItemsNamespaceURI)
            nsmgr.AddNamespace(PictureLibrariesNamespacePrefix, PictureLibrariesNamespaceURI)
            nsmgr.AddNamespace(WebPartsNamespacePrefix, WebPartsNamespaceURI)
            nsmgr.AddNamespace(DirectoryNamespacePrefix, DirectoryNamespaceURI)


            xmlnlist = xmldoc.SelectNodes("//z:row", nsmgr)

            For Each xmln In xmlnlist
                Dim title As String = xmln.Attributes("ows_Title").Value
                Dim description As String = xmln.Attributes("ows_Description").Value
            Next
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Awesome, that's exactly what I was looking for. Here is my final code for reference.

// Authentication settings
            string spUsername = ConfigSettings.SPUsername;
            string spPassword = ConfigSettings.SPPassword;
            string spDomain = ConfigSettings.SPDomain;

            Lists listService = new Lists();
            listService.Credentials = new System.Net.NetworkCredential(spUsername, spPassword, spDomain);
            listService.Url = ConfigSettings.SPListUrl;


            // List settings
            string listName = ConfigSettings.SPListGuid;
            string viewName = null;
            string rowLimit = null;
            string webID = null;

            XmlDocument xmlDoc = new XmlDocument();

            // List Query Caml
            XmlNode listQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            listQuery.InnerXml = "<Where>" +
                                    "<Eq>" +
                                        "<FieldRef Name='ID' />" +
                                        "<Value Type='Number'>" + _ServiceRequestID + "</Value>" +
                                    "</Eq>" +
                                 "</Where>";

            // List View Caml
            XmlNode listViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
            listViewFields.InnerXml = "<FieldRef Name='Title' />" +
                                      "<FieldRef Name='Description' />" +
                                      "<FieldRef Name='Status' />" +
                                      "<FieldRef Name='Resolution' />";

            // List Query Options Caml
            XmlNode listQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
            listQueryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" +
                                        "<DateInUtc>TRUE</DateInUtc>";

            XmlNode results = listService.GetListItems(listName, viewName, listQuery, listViewFields, rowLimit, listQueryOptions, webID);
           
            XmlNamespaceManager spsNameSpaces = new XmlNamespaceManager(xmlDoc.NameTable);
            spsNameSpaces.AddNamespace("s", "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882");
            spsNameSpaces.AddNamespace("dt", "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882");
            spsNameSpaces.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
            spsNameSpaces.AddNamespace("z", "#RowsetSchema");
            spsNameSpaces.AddNamespace("", "http://schemas.microsoft.com/sharepoint/soap/");


            XmlNodeList nodeList = results.SelectNodes("//z:row", spsNameSpaces);

            foreach (XmlNode node in nodeList)
            {
                lblTitle.Text = node.Attributes["ows_Title"].InnerText;
                lblDescription.Text = node.Attributes["ows_Description"].InnerText;
                lblStatus.Text = node.Attributes["ows_Status"].InnerText;
            }

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.