我就是这样做的(下面的代码已经过测试,下面提供了完整的源代码),首先创建一个具有公共属性的类
class Word
{
public string Base { get; set; }
public string Category { get; set; }
public string Id { get; set; }
}
出于演示目的,使用带有 INPUT_DATA 的 XDocument 加载,并使用lexicon查找元素名称。. .
XDocument doc = XDocument.Parse(INPUT_DATA);
XElement lex = doc.Element("lexicon");
确保有一个值并使用 linq 从中提取单词元素。. .
Word[] catWords = null;
if (lex != null)
{
IEnumerable<XElement> words = lex.Elements("word");
catWords = (from itm in words
where itm.Element("category") != null
&& itm.Element("category").Value == "verb"
&& itm.Element("id") != null
&& itm.Element("base") != null
select new Word()
{
Base = itm.Element("base").Value,
Category = itm.Element("category").Value,
Id = itm.Element("id").Value,
}).ToArray<Word>();
}
该where
语句检查类别元素是否存在并且类别值不为空,然后再次检查它是否是动词。然后检查其他节点是否也存在。. .
linq 查询将返回一个 IEnumerable<Typename> 对象,因此我们可以调用 ToArray<Typename>() 将整个集合强制转换为我们想要的类型。
然后打印得到 . . .
[Found]
Id: E0006429
Base: abandon
Category: verb
[Found]
Id: E0006524
Base: abolish
Category: verb
完整来源:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace test
{
class Program
{
class Word
{
public string Base { get; set; }
public string Category { get; set; }
public string Id { get; set; }
}
static void Main(string[] args)
{
XDocument doc = XDocument.Parse(INPUT_DATA);
XElement lex = doc.Element("lexicon");
Word[] catWords = null;
if (lex != null)
{
IEnumerable<XElement> words = lex.Elements("word");
catWords = (from itm in words
where itm.Element("category") != null
&& itm.Element("category").Value == "verb"
&& itm.Element("id") != null
&& itm.Element("base") != null
select new Word()
{
Base = itm.Element("base").Value,
Category = itm.Element("category").Value,
Id = itm.Element("id").Value,
}).ToArray<Word>();
}
//print it
if (catWords != null)
{
Console.WriteLine("Words with <category> and value verb:\n");
foreach (Word itm in catWords)
Console.WriteLine("[Found]\n Id: {0}\n Base: {1}\n Category: {2}\n",
itm.Id, itm.Base, itm.Category);
}
}
const string INPUT_DATA =
@"<?xml version=""1.0""?>
<lexicon>
<word>
<base>a</base>
<category>determiner</category>
<id>E0006419</id>
</word>
<word>
<base>abandon</base>
<category>verb</category>
<id>E0006429</id>
<ditransitive/>
<transitive/>
</word>
<word>
<base>abbey</base>
<category>noun</category>
<id>E0203496</id>
</word>
<word>
<base>ability</base>
<category>noun</category>
<id>E0006490</id>
</word>
<word>
<base>able</base>
<category>adjective</category>
<id>E0006510</id>
<predicative/>
<qualitative/>
</word>
<word>
<base>abnormal</base>
<category>adjective</category>
<id>E0006517</id>
<predicative/>
<qualitative/>
</word>
<word>
<base>abolish</base>
<category>verb</category>
<id>E0006524</id>
<transitive/>
</word>
</lexicon>";
}
}