【发布时间】:2020-03-20 16:18:30
【问题描述】:
我有许多复杂的 XML 文件,我想查询和搜索以获得一个值,下面是两个缩短的示例:
1
<textInfo>
<freeText>
<informationType>15</informationType>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>47</informationType>
</freeText>
<freeText>My required text</freeText>
</textInfo>
<textInfo>
<freeText>
<informationType>733</informationType>
<status>1</status>
</freeText>
</textInfo>
2
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>15</informationType>
<status>0</status>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>47</informationType>
</freeText>
<freeText>My required text</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<status>0</status>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>61</informationType>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>39</informationType>
</freeText>
<freeText>some text</freeText>
<freeText>some other text</freeText>
</textInfo>
需要的输出是:
标签 <freeText> 内的文本(我需要的文本) where tag <informationType> = (47)
尝试了多个 linq to xml 代码,但没有一个对我有用。 例如。
代码1
var query = from q in XDocument.Parse(requestInterceptor.LastResponseXML)
.Descendants("freeText")
where (bool)q.Element("informationType").Equals("47")
select q.Element("freeText").Value;
代码2
XDocument doc = XDocument.Parse(requestInterceptor.LastResponseXML); ;
var q = doc
.Descendants("freeText[1]")
.Where(ft => ((int?)ft.Element("informationType")) == 47);
Object.Type = q.ToString();
代码3
XmlDocument doc = new XmlDocument();
doc.LoadXml(requestInterceptor.LastResponseXML);
foreach (XmlNode node in doc.DocumentElement.SelectSingleNode("//textInfo/freeText[informationType>=47]/informationType"))
{
Object.Type = node.InnerText;
}
代码4
XmlDocument doc2 = new XmlDocument();
doc.LoadXml(requestInterceptor.LastResponseXML);
foreach (XmlNode node in doc2.SelectNodes("//textInfo/freeText[informationType>=47]/informationType"))
{
Object.Type = node.InnerText;
}
注意:我只是从 web 服务获取 xml。我没有将它存储在某处或将其作为 xml 文件。另请注意,这是 xml 的一部分,只有我需要获取信息
【问题讨论】:
-
尝试以下操作: List
freeText = doc.Descendants("freeText").Where(x => (string)x.Element("informationType") == "47").ToList ();
标签: c# xml-parsing linq-to-xml xmldocument xdoc