有条件地循环遍历XML文件,只在元素等于或等于值时读取数据



我有以下XML:-

<Scripts>
<ParseCheck>TEST</ParseCheck>
<COMMON>
<DBConnections>
<Connection name = "Book">
<Instance>SERVER1</Instance>
<DB>DB1</DB>
<Provider>SQLOLEDB</Provider>
<AuthType>Windows</AuthType>
<User></User>
<Pwd></Pwd>
</Connection>
<Connection name = "Report">
<Instance>SERVER2</Instance>
<DB>DB2</DB>
<Provider>SQLOLEDB</Provider>
<AuthType>Windows</AuthType>
<User></User>
<Pwd></Pwd>
</Connection>
</DBConnections>
</COMMON>

到目前为止,我的代码是:-

while (xmlreader.Read())
{
switch (xmlreader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
//Console.Write("<" + xmlreader.Name);
while (xmlreader.MoveToNextAttribute())
if (xmlreader.Value != "Book")
{
continue;
}
else
{
Console.Write(" " + xmlreader.Name + "='" + xmlreader.Value + "'");
}
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine(xmlreader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + xmlreader.Name);
Console.WriteLine(">");
break;
}
}

我的要求是只在Connection name="时捕获XML数据;书";忘记剩下的。我如何在C#中实现这一点?谢谢伊恩。。。。。。。。。。。。。。。。…

使用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:temptest.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, Connection> dict = doc.Descendants("Connection")
.Select(x => new Connection() {
name = (string)x.Attribute("name"),
instance = (string)x.Element("Instance"),
db = (string)x.Element("DB"),
provider = (string)x.Element("Provider"),
authType = (string)x.Element("AuthType"),
user = (string)x.Element("User"),
pwd = (string)x.Element("Pwd"),
})
.GroupBy(x => x.name, y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
Connection report = dict["Report"];
}
}
public class Connection
{
public string name { get; set; }
public string instance { get; set; }
public string db { get; set; }
public string provider { get; set; }
public string authType { get; set; }
public string user { get; set; }
public string pwd { get; set; }
}
}

最新更新