来源xml:
let appSettings = ConfigurationManager.AppSettings
let value = appSettings.Item(key)
我想读取用户uuid属性以及要追加到DataTable的所有节点。但我不知道如何读取属性和嵌套的xml(错误:“对象引用未设置为对象的实例。”)
我的代码:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:listUserResponse xmlns:ns="http://www.cisco.com/AXL/API/11.5">
<return>
<user uuid="{A00B47CC-0C4F-40E7-1E25-22E54FBA4596}">
<firstName>Name1</firstName>
<middleName />
<lastName>Surname1</lastName>
<primaryExtension>
<pattern>201</pattern>
</primaryExtension>
</user>
<user uuid="{834E86FA-FDC2-21FE-1E1E-FD164AF23B44}">
<firstName>Name2</firstName>
<middleName />
<lastName>Surname2</lastName>
<primaryExtension>
<pattern>202</pattern>
</primaryExtension>
</user>
<user uuid="{798E04E7-0E10-0278-6FAD-EA6A85EF2B2E}">
<firstName>Name3</firstName>
<middleName />
<lastName>Surname3</lastName>
<primaryExtension>
<pattern>203</pattern>
</primaryExtension>
</user>
</return>
</ns:listUserResponse>
</soapenv:Body>
</soapenv:Envelope>
谢谢你,最诚挚的问候, 彼得
答案 0 :(得分:0)
你可以使用这样的东西。
foreach (XmlNode xn in xnList)
{
string uuid = (xn as XmlElement).GetAttribute("uuid");
string firstName = xn.SelectSingleNode("./firstName").InnerText;
string middleName= xn.SelectSingleNode("./middleName").InnerText;
string lastName = xn.SelectSingleNode("./lastName").InnerText;
string primaryExtensionPattern = xn.SelectSingleNode("./primaryExtensionPattern /pattern").InnerText;
...
}
或者您可以考虑将Linq用于XML并使用XElement。对我来说,似乎更容易解析XML
答案 1 :(得分:0)
试试xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable datatableListUser = new DataTable();
datatableListUser.Clear();
datatableListUser.Columns.Add("uuid");
datatableListUser.Columns.Add("firstName", typeof(string));
datatableListUser.Columns.Add("middleName", typeof(string));
datatableListUser.Columns.Add("lastName", typeof(string));
datatableListUser.Columns.Add("primaryExtensionPattern", typeof(int));
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement user in doc.Descendants("user"))
{
datatableListUser.Rows.Add(new object[] {
(string)user.Attribute("uuid"),
(string)user.Element("firstName"),
(string)user.Element("middleName"),
(string)user.Element("lastName"),
(int)user.Descendants("pattern").FirstOrDefault()
});
}
}
}
}