在我开始之前这是我的第一篇文章,所以如果有什么我做错了或没做过请告诉我,我会编辑我的帖子
我有一份文件格式如下。
<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'>
<EventData>
<Data Name='SubjectUserSid'>S-1-0-0</Data>
<Data Name='SubjectUserName'>MACHINE$</Data>
<Data Name='SubjectDomainName'>DOMAIN</Data>
<Data Name='SubjectLogonId'>0x0</Data>
<Data Name='TargetUserSid'>S-1-0-0</Data>
<Data Name='TargetUserName'>username</Data>
<Data Name='TargetDomainName'>TDname</Data>
<Data Name='Status'>0x0</Data>
<Data Name='FailureReason'>%%2313</Data>
<Data Name='SubStatus'>0x0</Data>
<Data Name='LogonType'>10</Data>
</EventData>
</Event>
我遇到了一些问题,可以从XML中提取值(属性值和相应的元素值)。我是否需要为每个属性提供一个语句,或者我可以返回一个列表并循环显示这些值吗?
编辑:需要提取值,以便将它们发送到数据库。我想尝试使用LINQ,但Xpath可能会起作用
EDIT2:谢谢你的三个好答案,我没有要求。尚未提升答案的声誉,我需要在测试之前到达我的开发机器,但这真的看起来我正在寻找:)
答案 0 :(得分:2)
据我所知,您需要访问属性和值作为解析xml的示例。
不,你没有。使用下一个代码作为解析xml:的示例我是否需要为每个属性提供一个语句,或者我可以返回一个列表 并只是循环值?
//str contains your xml
XDocument xml = XDocument.Parse(str);
XNamespace ns = "http://schemas.microsoft.com/win/2004/08/events/event";
foreach (var node in xml.Descendants(ns + "Data"))
{
Console.WriteLine ("Name: " + (string)node.Attribute("Name") + "; "+
"Value: " + node.Value);
}
将打印:
Name: SubjectUserSid; Value: S-1-0-0
Name: SubjectUserName; Value: MACHINE$
Name: SubjectDomainName; Value: DOMAIN
Name: SubjectLogonId; Value: 0x0
Name: TargetUserSid; Value: S-1-0-0
Name: TargetUserName; Value: username
Name: TargetDomainName; Value: TDname
Name: Status; Value: 0x0
Name: FailureReason; Value: %%2313
Name: SubStatus; Value: 0x0
Name: LogonType; Value: 10
答案 1 :(得分:1)
XNamespace ns = "http://schemas.microsoft.com/win/2004/08/events/event";
var document = XDocument.Parse(
"<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'>" +
"<EventData>" +
" <Data Name='SubjectUserSid'>S-1-0-0</Data>" +
" <Data Name='SubjectUserName'>MACHINE$</Data>" +
" <Data Name='SubjectDomainName'>DOMAIN</Data>" +
" <Data Name='SubjectLogonId'>0x0</Data>" +
" <Data Name='TargetUserSid'>S-1-0-0</Data>" +
" <Data Name='TargetUserName'>username</Data>" +
" <Data Name='TargetDomainName'>TDname</Data>" +
" <Data Name='Status'>0x0</Data>" +
" <Data Name='FailureReason'>%%2313</Data>" +
" <Data Name='SubStatus'>0x0</Data>" +
" <Data Name='LogonType'>10</Data>" +
"</EventData>" +
"</Event>");
var q = from element in document.Root.Element(ns + "EventData").Elements(ns + "Data")
select new
{
Name = element.Attribute("Name").Value,
Value = element.Value
};
答案 2 :(得分:1)
获取每个元素的属性:
var attributes = from n in xml.Descendants("Data")
select n.Attributes("Name").Select(s => s.Value);
获取每个元素的数据:
var data = from n in xml.Descendants("EventData")
select n.Elements("Data").Select(s => s.Value);
或在一个查询中: -
var nodes = from n in xml.Descendants("EventData").Elements("Data")
select new
{
Data = n.Value,
Attribute = n.Attribute("Name").Value
};