Skip to main content
 首页 » 编程设计

c#之使用 XmlNode.selectSingleNode 选择一个节点

2024年02月23日18davidwang456

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

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:ErrorCode 或 rs:ErrorCode 时没有得到任何结果。

请您参考如下方法:

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>