我正在尝试使用LINQ将从GET请求检索到的XML文件解析为在线词典API。
文件:
<?xml version="1.0" encoding="utf-8"?>
<entry_list version="1.0">
<entry id="nanny">
<ew>nanny</ew>
<hw>nan*ny</hw>
<sound>
<wav>nanny001.wav</wav>
<wpr>!na-nE</wpr>
</sound>
<vr>
<vl>also</vl>
<va>nan*nie</va>
<sound>
<wav>nanny001.wav</wav>
<wpr>!na-nE</wpr>
</sound>
<pr>ˈna-nē</pr>
</vr>
<fl>noun</fl>
<in>
<il>plural</il>
<if>nannies</if>
</in>
<et>probably of baby-talk origin</et>
<def>
<date>1795</date>
<dt>:a child's nurse or caregiver</dt>
</def>
</entry>
<entry id="nanny goat">
<ew>nanny goat</ew>
<subj>AG#ZM</subj>
<hw>nanny goat</hw>
<fl>noun</fl>
<et>
<it>Nanny,</it>
nickname for
<it>Anne</it>
</et>
<def>
<date>1788</date>
<dt>:a female goat</dt>
</def>
</entry>
</entry_list>
我试图仅解析'def'的第一个实例,因为它是唯一匹配要定义的原始单词的实例。我不确定如何实现这一目标。 'def'块也可能如下所示:
<def>
<date>13th century</date>
<sn>1</sn>
<dt>
:a person who puts on a false appearance of
<d_link>virtue</d_link>
or religion
</dt>
<sn>2</sn>
<dt>
:a person who acts in contradiction to his or her stated beliefs or feelings
</dt>
</def>
在这种情况下,我不确定如何使用'sn'和amp; 'dt'分组并将它们放在一种格式中,可以很容易地输出它们原来的情侣。我目前的代码在这里: HttpWebRequest request =(HttpWebRequest)HttpWebRequest.Create([request url]); request.Method =“GET”;
string responseStr;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream _stream = response.GetResponseStream();
StreamReader sr = new StreamReader(_stream);
responseStr = sr.ReadToEnd();
sr.Close();
_stream.Close();
}
XDocument xdoc;
using (StringReader s = new StringReader(responseStr)) {
xdoc = XDocument.Load(s);
}
string word = (string)xdoc.Element("ew");
string pron = (string)xdoc.Element("pr");
string pos = (string)xdoc.Element("fl");
Console.WriteLine((string)xdoc.Element("sr"));
var definitions = (from d in xdoc.Root.Descendants("def")
select new {
entryNum = xdoc.Elements("sr").Select(a => a.Value).ToList(),
entryDef = xdoc.Elements("dt").Select(a => a.Value).ToList()
}).FirstOrDefault();
Console.WriteLine(String.Join(":", definitions.entryDef)); //output is blank
这是输出:
{ entryNum = System.Collections.Generic.List`1[System.String], entryDef = System.Collections.Generic.List`1[System.String] }
我试图输出子列表的内容,但输出为空白且没有显示任何值。
我想要实现的输出是一个通用列表,内容如下:{entryNum:entryDef, entryNum:entryDef}
所以我可以很容易地输出它:
儿童的护士或照顾者
- 醇>
此处的另一个定义