?
Solved

Getting Values From XmlNode

Posted on 2007-10-04
16
Medium Priority
?
1,380 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>
0
Comment
Question by:DuNuNuBatman
  • 9
  • 5
  • 2
16 Comments
 
LVL 35

Expert Comment

by:YZlat
ID: 20016137

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()
0
 
LVL 35

Expert Comment

by:YZlat
ID: 20016163
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

0
 
LVL 7

Expert Comment

by:joesthebighmoe
ID: 20016192
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;        
      }
0
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.

 
LVL 35

Expert Comment

by:YZlat
ID: 20016285
I think he means multiple attributes and not multiple rows
0
 

Author Comment

by:DuNuNuBatman
ID: 20016354
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:
0
 
LVL 7

Expert Comment

by:joesthebighmoe
ID: 20016385
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;        
      }
0
 
LVL 35

Expert Comment

by:YZlat
ID: 20016469
my second example will aloow you to get the results for multiple rows and then loop through them
0
 
LVL 35

Expert Comment

by:YZlat
ID: 20016499
the error is because of a z: prefix
0
 

Author Comment

by:DuNuNuBatman
ID: 20016559
How do I fix that?
0
 
LVL 35

Expert Comment

by:YZlat
ID: 20016569
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





0
 

Author Comment

by:DuNuNuBatman
ID: 20016604
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));
0
 
LVL 35

Expert Comment

by:YZlat
ID: 20016683
here is just what you need:

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

Author Comment

by:DuNuNuBatman
ID: 20016707
which one am I looking for?
0
 
LVL 35

Expert Comment

by:YZlat
ID: 20016746
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
0
 
LVL 35

Accepted Solution

by:
YZlat earned 2000 total points
ID: 20016795

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);

//Since the XML returned by SPS contains namespace prefixes - we need to create a XmlNamespaceManager
            string ListItemsNamespacePrefix  = "z";
            string ListItemsNamespaceURI  = "#RowsetSchema";

            string PictureLibrariesNamespacePrefix = "s";
            string PictureLibrariesNamespaceURI  = "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882";

            string WebPartsNamespacePrefix = "dt";
            string WebPartsNamespaceURI = "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882";

            string DirectoryNamespacePrefix  = "rs";
            string DirectoryNamespaceURI = "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
            Xml.XmlNamespaceManager nsmgr = new Xml.XmlNamespaceManager(xmldoc.NameTable);

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


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


            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));
0
 

Author Comment

by:DuNuNuBatman
ID: 20016904
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;
            }
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses
Course of the Month14 days, 3 hours left to enroll

807 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