Accessing xmlNodeList with partial namespaces(Xpath) - c#

I have been digging through every example I can find related to Xpath and XML parsing. I can't find a close enough example to the XML I have to deal with that makes any sense to me. I am having an extremely difficult time wrapping my head around Xpath in particular but also XML parsing in a more general sense. The complexity of the file I'm working with is not making it easier to understand.
I have an XML file coming from a remote source which I have no control over.
The file is:
<AssetWarrantyDTO xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Dell.Support.AssetsExternalAPI.Web.Models.V1.Response">
<AdditionalInformation i:nil="true"/>
<AssetWarrantyResponse>
<AssetWarrantyResponse>
<AssetEntitlementData>
<AssetEntitlement>
<EndDate>2010-12-20T23:59:59</EndDate>
<EntitlementType>EXTENDED</EntitlementType>
<ItemNumber>983-4252</ItemNumber>
<ServiceLevelCode>ND</ServiceLevelCode>
<ServiceLevelDescription>Next Business Day Onsite</ServiceLevelDescription>
<ServiceLevelGroup>5</ServiceLevelGroup>
<ServiceProvider>UNY</ServiceProvider>
<StartDate>2008-12-21T00:00:00</StartDate>
</AssetEntitlement>
<AssetEntitlement>
<EndDate>2010-12-20T23:59:59</EndDate>
<EntitlementType>EXTENDED</EntitlementType>
<ItemNumber>987-1139</ItemNumber>
<ServiceLevelCode>TS</ServiceLevelCode>
<ServiceLevelDescription>ProSupport</ServiceLevelDescription>
<ServiceLevelGroup>8</ServiceLevelGroup>
<ServiceProvider>DELL</ServiceProvider>
<StartDate>2008-12-21T00:00:00</StartDate>
</AssetEntitlement>
<AssetEntitlement>
<EndDate>2008-12-20T23:59:59</EndDate>
<EntitlementType>INITIAL</EntitlementType>
<ItemNumber>984-0210</ItemNumber>
<ServiceLevelCode>ND</ServiceLevelCode>
<ServiceLevelDescription>Next Business Day Onsite</ServiceLevelDescription>
<ServiceLevelGroup>5</ServiceLevelGroup>
<ServiceProvider>UNY</ServiceProvider>
<StartDate>2007-12-20T00:00:00</StartDate>
</AssetEntitlement>
<AssetEntitlement>
<EndDate>2008-12-20T23:59:59</EndDate>
<EntitlementType>INITIAL</EntitlementType>
<ItemNumber>987-1308</ItemNumber>
<ServiceLevelCode>TS</ServiceLevelCode>
<ServiceLevelDescription>ProSupport</ServiceLevelDescription>
<ServiceLevelGroup>8</ServiceLevelGroup>
<ServiceProvider>DELL</ServiceProvider>
<StartDate>2007-12-20T00:00:00</StartDate>
</AssetEntitlement>
</AssetEntitlementData>
<AssetHeaderData>
<BUID>11</BUID>
<CountryLookupCode>US</CountryLookupCode>
<CustomerNumber>64724056</CustomerNumber>
<IsDuplicate>false</IsDuplicate>
<ItemClassCode>`U060</ItemClassCode>
<LocalChannel>17</LocalChannel>
<MachineDescription>Precision T3400</MachineDescription>
<OrderNumber>979857987</OrderNumber>
<ParentServiceTag i:nil="true"/>
<ServiceTag>7P3VBU1</ServiceTag>
<ShipDate>2007-12-20T00:00:00</ShipDate>
</AssetHeaderData>
<ProductHeaderData>
<LOB>Dell Precision WorkStation</LOB>
<LOBFriendlyName>Precision WorkStation</LOBFriendlyName>
<ProductFamily>Desktops & All-in-Ones</ProductFamily>
<ProductId>precision-t3400</ProductId>
<SystemDescription>Precision T3400</SystemDescription>
</ProductHeaderData>
</AssetWarrantyResponse>
</AssetWarrantyResponse>
<ExcessTags>
<BadAssets xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
</ExcessTags>
<InvalidBILAssets>
<BadAssets xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
</InvalidBILAssets>
<InvalidFormatAssets>
<BadAssets xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
</InvalidFormatAssets>
</AssetWarrantyDTO>
Here is the Final code not including the setting of the URI variable for the API URL.
protected void Unnamed1_Click(object sender, EventArgs e)
{
string Serial = TextBox1.Text.ToUpper();
URI = String.Format(URI, Serial);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
CookieContainer aCookie = new CookieContainer();
request.CookieContainer = aCookie;
WebResponse pageResponse = request.GetResponse();
Stream responseStream = pageResponse.GetResponseStream();
string xml = string.Empty;
using (StreamReader streamRead = new StreamReader(responseStream))
{
xml = streamRead.ReadToEnd();
}
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml(xml);
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length - 1;
xml = xml.Remove(0, lastIndexOfUtf8);
//Label2.Text = "BOM found.";
}
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc1.NameTable);
nsmgr.AddNamespace("j", "http://schemas.datacontract.org/2004/07/Dell.Support.AssetsExternalAPI.Web.Models.V1.Response");
XmlNodeList nodes = doc1.SelectNodes(".//j:AssetWarrantyResponse/j:AssetWarrantyResponse/j:AssetEntitlementData", nsmgr);
//Make a list to hold the start dates
System.Collections.ArrayList startDates = new System.Collections.ArrayList();
//Make a list to hold the end dates
System.Collections.ArrayList endDates = new System.Collections.ArrayList();
//Create a regex for finding just the date and discarding the time value which can alter tha date if the time is 24:00 (euro standard)
Regex r = new Regex(#"\d{4}-\d{1,2}-\d{1,2}", RegexOptions.IgnoreCase);
//Set the culture to format the date as US region
CultureInfo dtFormat = new CultureInfo("en-US", false);
foreach (XmlNode node in nodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{
string startDate = childNode["StartDate"].InnerText;
if (startDate != null)
{
MatchCollection mcl1 = r.Matches(startDate);
startDates.Add(DateTime.Parse(mcl1[0].ToString(), dtFormat));
}
string endDate = childNode["EndDate"].InnerText;
if (endDate != null)
{
MatchCollection mcl2 = r.Matches(endDate);
endDates.Add(DateTime.Parse(mcl2[0].ToString(), dtFormat));
}
}
startDates.Sort();
endDates.Sort();
DateTime wStartDate = new DateTime();
DateTime wEndDate = new DateTime();
//if (dates.Count > 1) wStartDate = (DateTime)dates[dates.Count - 1];
if (startDates.Count >= 1) wStartDate = (DateTime)startDates[0];
Label1.Text = wStartDate.ToString("MM/dd/yyyy");
if (endDates.Count >= 1) wEndDate = (DateTime)endDates[endDates.Count - 1];
Label2.Text = wEndDate.ToString("MM/dd/yyyy");
//Label2.Text = tempc;
//Label3.Text = feels;
}
nodes = doc1.SelectNodes(".//j:AssetWarrantyResponse/j:AssetWarrantyResponse/j:AssetHeaderData", nsmgr);
foreach (XmlNode node in nodes)
{
try
{
string custNumber = node["CustomerNumber"].InnerText;
string model = node["MachineDescription"].InnerText;
string orderNumber = node["OrderNumber"].InnerText;
string serialNumber = node["ServiceTag"].InnerText;
Label3.Text = custNumber;
Label4.Text = model;
Label5.Text = orderNumber;
Label6.Text = serialNumber;
}
catch (Exception ex)
{
dbgLabel.Text = ex.Message;
}
}
}

You are looking for AssetWarrantyResponse in namespace http://www.w3.org/2001/XMLSchema-instance (the namespace you have bound to prefix "i") but it is actually in namespace http://schemas.datacontract.org/2004/07/Dell.Support.AssetsExternalAPI.Web.Models.V1.Response. Bind a prefix to that namespace (anything will do, e.g "p") and use that prefix in your query, e.g. p:AssetWarrantyResponse, and similarly for other element names.
I wonder if you are spending too much time trying to look for example code that exactly matches what you want to do, and not enough time studying the underlying concepts of the language so that you can apply them to your own problems. Get some good XML books and read them.
There's another problem with your XPath, which is the "/" at the end of the path. That's invalid syntax. If that's the cause of the error then I'm not very impressed with your XPath processor's diagnostics.

Related

How to get XML data: SenderNumber and TextDecoded from each node in C#

So I have .xml file generated by network device. This .xml is looking like that :
<xml>
<messages>
<item>
<UpdatedInDB> 2019-01-14 15:25:05 < /UpdatedInDB>
<ReceivingDateTime>2018-10-22 09:53:51</ReceivingDateTime>
<Text>004B0075006C0074007500720061</Text>
<SenderNumber>+420000000000</SenderNumber>
<Coding>Default_No_Compression</Coding>
<UDH/>
<SMSCNumber>+420000000000</SMSCNumber>
<Class>-1</Class>
<TextDecoded>Kultura</TextDecoded>
<ID>29</ID>
<RecipientID></RecipientID>
<Processed>t</Processed>
<id_folder>1</id_folder>
<readed>true</readed>
<oid/>
<Status>0</Status>
</item>
<item>
<UpdatedInDB> 2019-01-14 15:25:05 < /UpdatedInDB>
<ReceivingDateTime>2018-10-22 09:53:51</ReceivingDateTime>
<Text>004B0075006C0074007500720061</Text>
<SenderNumber>+420000000000</SenderNumber>
<Coding>Default_No_Compression</Coding>
<UDH/>
<SMSCNumber>+420000000000</SMSCNumber>
<Class>-1</Class>
<TextDecoded>Kultura</TextDecoded>
<ID>29</ID>
<RecipientID></RecipientID>
<Processed>t</Processed>
<id_folder>1</id_folder>
<readed>true</readed>
<oid/>
<Status>0</Status>
</item>
</message>
</xml>
How do I get SenderNumber and textDecoded from each node?
I managed to get data only from first node using this
{
string baseUrl = "http://192.168.253.160/index.php/http_api/read_sms";
WebClient client = new WebClient();
client.QueryString.Add("login", "admin");
client.QueryString.Add("pass", "password");
client.QueryString.Add("folder", "inbox");
client.QueryString.Add("responsetype", "xml");
client.QueryString.Add("unread", "1");
/*client.QueryString.Add("to", cislo);
client.QueryString.Add("message", text);*/
client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
Stream receivedStream = client.OpenRead(baseUrl);
StreamReader reader = new StreamReader(receivedStream);
string result = reader.ReadToEnd();
receivedStream.Close();
reader.Close();
//parsing
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
string cislo = "0";
string zprava = "0";
XmlNodeList number = doc.GetElementsByTagName("SenderNumber");
for (int i = 0; i < number.Count; i++)
{
cislo = number[i].InnerXml;
}
XmlNodeList text = doc.GetElementsByTagName("TextDecoded");
for (int i = 0; i < text.Count; i++)
{
zprava = text[i].InnerXml;
}
MessageBox.Show(cislo);
MessageBox.Show(zprava);
}
The problem is that I read only unread messages from api. If I read only the first node I will lose the rest and will not be there for the second time because they will be 'read' already.
Anyone who can give me a advice for this? I was trying to google but didn't really find anything what would work for me.
Thank you very much.
Inside of your for loops, you always replace the value of your variables (cislo or zprava), so in the end you're only going to see the last values parsed. If you want to keep track of them all, either store them in a list or array, or append them directly to the string. For example,
var cislo = new List<string>();
var zprava = new List<string>();
XmlNodeList number = doc.GetElementsByTagName("SenderNumber");
for (int i = 0; i < number.Count; i++)
{
cislo.Add(number[i].InnerXml);
}
XmlNodeList text = doc.GetElementsByTagName("TextDecoded");
for (int i = 0; i < text.Count; i++)
{
zprava.Add(text[i].InnerXml);
}
MessageBox.Show(string.Join(", ", cislo));
MessageBox.Show(string.Join(", ", zprava));
You can use XElement to fetch data and pack it into anonymous type:
var xml = XElement.Parse(result);
var data = xml
.Elements()
.Select(e => new { SenderNumber = e.Element("SenderNumber").Value,
TextDecoded = e.Element("TextDecoded").Value });
// iterate over collection
data.ToList().ForEach(e => Console.WriteLine($"Sender: {e.SenderNumber}, " +
$"TextDecoded: {e.TextDecoded}"));

How to retrieve all Elements from XML file using c#

I am trying to retrieve all elements from an XML file, but I just can reach one, is there any way I can retrieve all?
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (XmlReader reader = XmlReader.Create(new StreamReader(objResponse.GetResponseStream())))
{
while (reader.Read())
{
#region Get Credit Score
//if (reader.ReadToDescendant("results"))
if (reader.ReadToDescendant("ssnMatchIndicator"))
{
string ssnMatchIndicator = reader.Value;
}
if (reader.ReadToDescendant("fileHitIndicator"))
{
reader.Read();//this moves reader to next node which is text
result = reader.Value; //this might give value than
Res.Response = true;
Res.SocialSecurityScore = result.ToString();
//break;
}
else
{
Res.Response = false;
Res.SocialSecurityScore = "Your credit score might not be available. Please contact support";
}
#endregion
#region Get fileHitIndicator
if (reader.ReadToDescendant("fileHitIndicator"))
{
reader.Read();
Res.fileHitIndicator = reader.Value;
//break;
}
#endregion
}
}
Can somebody help me out with this issue?
I am also using objResponse.GetResponseStream() because the XML comes from a response from server.
Thanks a lot in advance.
Try this :
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode ;
int i = 0;
string str = null;
FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("Product");
for (i = 0; i <= xmlnode.Count - 1; i++)
{
xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
MessageBox.Show (str);
}
I don't know why what you're doing is not working, but I wouldn't use that method. I've found the following to work well. Whether you're getting the xml from a stream, just put it into a string and bang...
StreamReader reader = new StreamReader(sourcepath);
string xml = reader.ReadToEnd();
reader.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList list = doc.GetElementsByTagName("*");
foreach (XmlNode nd in list)
{
switch (nd.Name)
{
case "ContactID":
var ContactIdent = nd.InnerText;
break;
case "ContactName":
var ContactName = nd.InnerText;
break;
}
}
To capture what is between the Xml tags, if there are no child Xml tags, use the InnerText property, e.g. XmlNode.InnerText. To capture what is between the quotes in the nodes' attributes, use XmlAttribute.Value.
As for iterating through the attributes, if one of your nodes has attributes, such as the elements "Name", "SpectralType" and "Orbit" in the Xml here:
<System>
<Star Name="Epsilon Eridani" SpectralType="K2v">
<Planets>
<Planet Orbit="1">Bill</Planet>
<Planet Orbit="2">Moira</Planet>
</Planets>
</Star>
</System>
Detect them using the Attributes property, and iterate through them as shown:
if (nd.Attributes.Count > 0)
{
XmlAttributeCollection coll = nd.Attributes;
foreach (XmlAttribute cn in coll)
{
switch (cn.Name)
{
case "Name":
thisStar.Name = cn.Value;
break;
case "SpectralType":
thisStar.SpectralClass = cn.Value;
break;
}
}
}
You might find some more useful information HERE.

Unassigned local variables

I bet these types of questions are the most common, however after trying what it said in a few other questions and still getting errors, I came here. I'm getting the following errors:
Use of unassigned local variable 'nodeRss'
Use of unassigned local variable 'nodeChannel'
class Program
{
static void Main(string[] args)
{
XmlTextReader rssReader;
XmlDocument rssDoc;
XmlNode nodeRss;
XmlNode nodeChannel;
String title;
String text;
HttpWebRequest http = WebRequest.Create("http://www.aerolitegaming.com/login/login") as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.AllowAutoRedirect = true;
http.ContentType = "application/x-www-form-urlencoded";
string postData="login=SNIP&register=0&password=SNIP&remember=1&cookie_check=0&redirect=forum%2F&_xfToken=";
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
int y = (int)httpResponse.StatusCode;
http = WebRequest.Create("http://www.aerolitegaming.com/forum") as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
http.AllowAutoRedirect=false;
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
rssReader = new XmlTextReader("http://aerolitegaming.com/forums/in-game-reports.132/index.rss");
rssDoc = new XmlDocument();
rssDoc.Load(rssReader);
// Loop for the <rss> tag
for (int i = 0; i < rssDoc.ChildNodes.Count; i++)
{
// If it is the rss tag
if (rssDoc.ChildNodes[i].Name == "rss")
{
// <rss> tag found
nodeRss = rssDoc.ChildNodes[i];
}
}
// Loop for the <channel> tag
for (int i = 0; i < nodeRss.ChildNodes.Count; i++)
{
// If it is the channel tag
if (nodeRss.ChildNodes[i].Name == "channel")
{
// <channel> tag found
nodeChannel = nodeRss.ChildNodes[i];
}
}
// Set the labels with information from inside the nodes
title = "Title: " + nodeChannel["title"].InnerText;
text = "Description: " + nodeChannel["description"].InnerText;
Console.WriteLine(title);
Console.WriteLine(text);
}
}
The nodeRss variable is an assigned in an if statement here:
if (rssDoc.ChildNodes[i].Name == "rss")
{
// <rss> tag found
nodeRss = rssDoc.ChildNodes[i];
}
I'm sure that you never fail to get into that if statement, and so you aren't worried about the lack of initialization. However, the compiler doesn't know that, and so is complaining that nodeRss is never assigned (because it isn't guaranteed to be).
In reality, I highly doubt you are actually guaranteed to get into that if statement, and so you should assign it a default value (null is ok) and check against that value before using the variable.
nodeChannel is running into the same problem.
Because you assign these variables values in a different scope { }.
To prevent the messages, simply give them values.
XmlNode nodeRss = null;
XmlNode nodeChannel = null;
It looks like the you are only assigning values to the two variables under certain conditions, which would lead to them not being set if those conditions have not been met.

Why does XDocument.Parse throw NotSupportedException?

I am trying to parse xml data using XDocument.Parse wchich throws NotSupportedException, just like in topic: Is XDocument.Parse different in Windows Phone 7? and I updated my code according to posted advice, but it still doesn't help. Some time ago I parsed RSS using similar (but simpler) method and that worked just fine.
public void sList()
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string url = "http://eztv.it";
Uri u = new Uri(url);
client.DownloadStringAsync(u);
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
string s = e.Result;
s = cut(s);
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
XDocument document = null;// XDocument.Parse(s);//Load(s);
using (XmlReader reader = XmlReader.Create(new StringReader(e.Result), settings))
{
document = XDocument.Load(reader); // error thrown here
}
// ... rest of code
}
catch (Exception ex)
{
MessageBox.Show( ex.Message);
}
}
string cut(string s)
{
int iod = s.IndexOf("<select name=\"SearchString\">");
int ido = s.LastIndexOf("</select>");
s = s.Substring(iod, ido - iod + 9);
return s;
}
When I substitute string s for
//string s = "<select name=\"SearchString\"><option value=\"308\">10 Things I Hate About You</option><option value=\"539\">2 Broke Girls</option></select>";
Everything works and no exception is thrown, so what do I do wrong?
There are special symbols like '&' in e.Result.
I just tried replace this symbols (all except '<', '>', '"') with HttpUtility.HtmlEncode() and XDocument parsed it
UPD:
I didn't want to show my code, but you left me no chance :)
string y = "";
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '<' || s[i] == '>' || s[i] == '"')
{
y += s[i];
}
else
{
y += HttpUtility.HtmlEncode(s[i].ToString());
}
}
XDocument document = XDocument.Parse(y);
var options = (from option in document.Descendants("option")
select option.Value).ToList();
It's work for me on WP7. Please, do not use this code for html conversion. I wrote it quickly just for test purposes

Sharepoint via web service : checking if item exists in list

Because Microsoft did not include a way to have unique constraints in sharepoint, this has to be done manually.
I am inserting items into a sharepoint list via a web service method.
How can I check if an existing list item already exists with the same field ID value?
I've learnt I should be using wsLists.getListitems web service method, but its not exactly "user friendly". MSDN documentation is again not really great at explaining what should be an easy thing to do.
private bool itemDoesntExist()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"ID\" /><Value Type=\"Text\">" + this.ID + "</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
XmlNode items = this.wsLists.GetListItems(this.ListName , string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, null);
if (items.ChildNodes[1].Attributes["ItemCount"].Value == "0")
{
return true;
}
else
{
return false;
}
}
Here's a procedure I wrote 2 years ago that pulls the ID of a document with a given filename... I think you could easily revise it to return true/false if a given ID exists in a list.
protected string GetDocumentID(Lists.Lists ls, string ListGUID, string FileName)
{
string strDocumentID = "-1";
string strViewGUID = "";
string strRowLimit = "50000";
XmlDocument xmlDoc = new XmlDocument();
XmlNode query = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode viewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode queryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
query.InnerXml = "";
viewFields.InnerXml = "";
queryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>";
System.Xml.XmlNode nodeListItems = ls.GetListItems(ListGUID, strViewGUID, query, viewFields, strRowLimit, queryOptions, null);
XmlDocument doc = new XmlDocument();
doc.LoadXml(nodeListItems.InnerXml);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("z", "#RowsetSchema");
nsmgr.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
foreach (XmlNode node in doc.SelectNodes("/rs:data/z:row", nsmgr))
{
if (node.Attributes["ows_LinkFilename"].Value == FileName)
{
strDocumentID = node.Attributes["ows_ID"].Value;
break;
}
}
return strDocumentID;
}
Here's the code that calls it...
Lists.Lists ls = new Lists.Lists();
ls.PreAuthenticate = true;
ls.Credentials = System.Net.CredentialCache.DefaultCredentials;
ls.Url = SharePointSiteURL + #"/_vti_bin/lists.asmx";
string DocID = GetDocumentID(ls, ListGUID, FileName);

Categories