<?xml version="1.0"?>
<Rules>
<Rule id="001">
<Rule1> name="name1" ruleAttrib="rule1Attribute"</Rule1>
<Rule2> name="name2" </Rule2>
</Rule>
<Rule id="002">
<Rule3>name="name3"</Rule3>
<Rule4>name="name4"</Rule4>
<Rule5>name="name5" ruleAttrib="rule2Attribute"</Rule5>
</Rule>
<Rule id="003">
<Rule6>name="name6"</Rule6>
<Rule7>name="name7" ruleAttrib=""</Rule7>
</Rule>
<Rule id="004">
<Rule8>name="name8"</Rule8>
<Rule9>name="name9" </Rule9>
</Rule>
<Rule id="005" />
<Rule id="006">
<Rule10>name="name10"</Rule10>
<Rule11>name="name11" ruleAttrib="rule4Attribute"</Rule11>
<Rule12>name="name12"</Rule12>
</Rule>
</Rules>
无法打印特定属性的属性值列表,例如(“ ruleAttrib”)
预期的输出列表:-
索引3上方为空,因为ID = 003的规则包含ruleAttrib,其中不包含任何内容。
尝试代码:-
XDocument xdoc = new XDocument.Load(xmlPath);
List<XElement> ruleGroupList = xdoc.Descendants("Rule").ToList();
foreach (var item in ruleGroupList)
{
if (item.Descendants().Attributes("ruleAttrib").exist)
{
List<XAttribute> ruleAttriblist = item.Descendants().Attributes("ruleAttrib").ToList();
Console.WriteLine(ruleAttriblist );
}
}
Console.ReadLine();
答案 0 :(得分:0)
foreach (var item in ruleGroupList)
{
if (item.Descendants().Attributes("ruleAttrib").Count() != 0)
{
List<XAttribute> ruleAttriblist = item.Descendants().Attributes("ruleAttrib").ToList();
foreach (var item in ruleAttriblist)
{
Console.WriteLine(item.Value);
}
}
}
Console.ReadLine();
工作正常...根据预期输出。
答案 1 :(得分:0)
尝试以下使用xml linq和regex的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants()
.Where(x => (x.NodeType == XmlNodeType.Element) && (x.Elements().Count() == 0))
.Select(x => GetAttributes((string)x))
.Where(x => x != null)
.Select(x => new { name = x.Groups["name"].Value, rule = x.Groups["rule"].Value })
.ToList();
}
static Match GetAttributes(string innertext)
{
string pattern = "name=\"(?'name'[^\"]+)\"\\s+ruleAttrib=\"(?'rule'[^\"]*)";
Match match = Regex.Match(innertext, pattern);
if (!match.Success) match = null;
return match;
}
}
}
答案 2 :(得分:0)
ruleAttribute不是属性,但实际上是元素的值(内部文本)。
您可以使用Linq
解析Element
(Rulexx),然后使用Regex
解析与ruleAttrib
关联的值。
List<XElement> ruleGroupList = xdoc.Root.Descendants("Rule").ToList();
var regex = new Regex("ruleAttrib='(?<value>\\S*)'");
var result = ruleGroupList.Elements()
.Select(x=>x.Value)
.Where(x=> regex.IsMatch(x))
.Select(x=>regex.Match(x).Groups["value"].Value);
输出
如果您要使用格式“ 1.rule1Attribute”,则可以使用
var result = ruleGroupList.Elements()
.Select(x=>x.Value)
.Where(x=> regex.IsMatch(x))
.Select((x,index)=>$"{index+1}.{regex.Match(x).Groups["value"].Value}");