使用XmlNode.selectSingleNode选择一个节点

时间:2011-09-15 13:40:19

标签: c# .net xml xpath

我使用以下代码将项目添加到SP列表,使用Web服务:

XmlNode returnValue = lists.UpdateListItems("Facturas", batchElement);
XmlNodeList errors = returnValue.SelectNodes("/Results");
if (errors.Count != 1)
{
   Console.WriteLine("errors.Count es " + errors.Count);
   Console.ReadKey();
   return -1;
}
Console.WriteLine("Error " + errors[0].Value + " -> " + int.Parse(errors[0].Value));

errors.OuterXml返回以下XML(z:row的属性已被省略)

<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
  <Result ID="1,New" xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <ErrorCode>0x00000000</ErrorCode>
    <ID />
    <z:row ows_ContentTypeId="0x010031045FE2D0730F499569DE68AFDB3F0B" ... xmlns:z="#RowsetSchema" />
  </Result>
</Results>

当我运行代码时,我总是得到errors.Count为0.我已经尝试了以下SelectNodes方法的参数:

ErrorCode
//ErrorCode
/Results
Results
*[local-name() = 'ErrorCode']
/*[local-name() = 'Results']

另外,我将代码更改为:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.microsoft.com/sharepoint/soap/");
nsmgr.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
nsmgr.AddNamespace("z", "#RowsetSchema");
XmlNode returnValue = lists.UpdateListItems("Facturas", batchElement);
XmlNodeList errors = returnValue.SelectNodes("soap:ErrorCode", nsmgr);

并没有得到任何查询soap:ErrorCoders:ErrorCode的内容。

1 个答案:

答案 0 :(得分:4)

var doc = new XmlDocument();
doc.Load("1.xml");


var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.microsoft.com/sharepoint/soap/");

var results = doc.SelectSingleNode("/soap:Results", nsmgr);
var errorcode = doc.SelectSingleNode("/soap:Results/soap:Result/soap:ErrorCode", nsmgr);

Console.WriteLine(errorcode.InnerText);

示例XML:

<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
  <Result ID="1,New" xmlns="http://schemas.microsoft.com/sharepoint/soap/">
    <ErrorCode>0x00000000</ErrorCode>
    <ID />
    <z:row ows_ContentTypeId="0x010031045FE2D0730F499569DE68AFDB3F0B" xmlns:z="#RowsetSchema" />
  </Result>
</Results>