如何在C#中循环遍历以下XML:

huangapple go评论71阅读模式
英文:

How to foreach following xml in c#

问题

List<Result> r = new List<Result>();
XDocument doc = XDocument.Parse(xmlResult);
foreach (var item in doc.Descendants("RESPONSE"))
{
    r.Add(new Result
    {
        SearchValue = item.Element("QUERY1").Attribute("searched").Value,
        SearchResult = item.Element("QUERY1").Value
    });
    r.Add(new Result
    {
        SearchValue = item.Element("QUERY2").Attribute("searched").Value,
        SearchResult = item.Element("QUERY2").Value
    });
    r.Add(new Result
    {
        SearchValue = item.Element("QUERY3").Attribute("searched").Value,
        SearchResult = item.Element("QUERY3").Value
    });
    r.Add(new Result
    {
        SearchValue = item.Element("QUERY4").Attribute("searched").Value,
        SearchResult = item.Element("QUERY4").Value
    });
    r.Add(new Result
    {
        SearchValue = item.Element("QUERY5").Attribute("searched").Value,
        SearchResult = item.Element("QUERY5").Value
    });
    r.Add(new Result
    {
        SearchValue = item.Element("QUERY6").Attribute("searched").Value,
        SearchResult = item.Element("QUERY6").Value
    });
    r.Add(new Result
    {
        SearchValue = item.Element("QUERY7").Attribute("searched").Value,
        SearchResult = item.Element("QUERY7").Value
    });
}

这是你提供的代码的更新版本,用于将搜索键和搜索结果添加到 Result 对象的列表中。

英文:

I have following xml result

&lt;?xml version=&quot;1.0&quot; encoding=&quot;windows-1254&quot; ?&gt;
&lt;RESPONSE&gt;
  &lt;VALIDATION&gt;1&lt;/VALIDATION&gt;
  &lt;QUERY1 searched=&quot;12345&quot;&gt;0&lt;/QUERY1&gt;
  &lt;QUERY2 searched=&quot;aaaaa&quot;&gt;2&lt;/QUERY2&gt;
  &lt;QUERY3 searched=&quot;44444&quot;&gt;2&lt;/QUERY3&gt;
  &lt;QUERY4 searched=&quot;99999&quot;&gt;0&lt;/QUERY4&gt;
  &lt;QUERY5 searched=&quot;number&quot;&gt;0&lt;/QUERY5&gt;
  &lt;QUERY6 searched=&quot;bar&quot;&gt;0&lt;/QUERY6&gt;
  &lt;QUERY7 searched=&quot;foo&quot;&gt;1&lt;/QUERY7&gt;
&lt;/RESPONSE&gt;
&lt;/xml&gt;

I have following class

public class Result{
 public string SearchValue {get;set;}
 public string SearchResult {get;set;}
}

And this code

...
List&lt;Result&gt; r = new List&lt;Result&gt;();
XDocument doc = XDocument.Parse(xmlResult);
foreach( var item in doc.Descendants(&quot;RESPONSE&quot;)){
 r.Add(new Result{
   SearchValue = item.Attribute(&quot;searched&quot;).Value,
   SearchResult = item.Element(&quot;QUERY?&quot;).Value
 });
}
...

How to get all searched keys and searched result to list object?

答案1

得分: 2

I suspect you want something like:

XDocument doc = XDocument.Parse(xmlResult);
var results = doc.Root
    .Elements()
    .Where(e => e.Name.LocalName.StartsWith("QUERY"))
    .Select(e => new Result {
        SearchValue = (string) e.Attribute("searched"),
        SearchResult = e.Value
    })
    .ToList();

That assumes that:

  • You only care about elements that are direct children of the root element
  • You want to ignore any elements whose local names don't start with "QUERY"
  • You're okay with handling a missing searched attribute by creating a Result object with a null value for SearchValue
  • You're okay with SearchResult being the concatenation of all text nodes in the query element
英文:

I suspect you want something like:

XDocument doc = XDocument.Parse(xmlResult);
var results = doc.Root
    .Elements()
    .Where(e =&gt; e.Name.LocalName.StartsWith(&quot;QUERY&quot;))
    .Select(e =&gt; new Result {
        SearchValue = (string) e.Attribute(&quot;searched&quot;),
        SearchResult = e.Value
    })
    .ToList();

That assumes that:

  • You only care about elements that are direct children of the root element
  • You want to ignore any elements whose local names don't start with "QUERY"
  • You're okay with handling a missing searched attribute by creating a Result object with a null value for SearchValue
  • You're okay with SearchResult being the concatenation of all text nodes in the query element

答案2

得分: 1

你可以使用XPath选择降序元素,使用以下代码://RESPONSE/*[starts-with(name(),'QUERY')]

使用LINQ 重写后的代码如下:

var nodes = doc.SelectNodes("//RESPONSE/*[starts-with(name(),'QUERY')]")
               .Cast<XmlNode>();

var query = (from elm in nodes
             where elm.Attributes.Cast<XmlAttribute>().Any(x => x.Name == "searched")
             select new Result()
             {
                 SearchValue = elm.Attributes["searched"].Value,
                 SearchResult = elm.InnerText
             }).ToList();

你可以在 dotnetfiddle.net 上查看示例。

英文:

You can select the descending elements using xpath //RESPONSE/*[starts-with(name(),&#39;QUERY&#39;)]

	foreach(XmlNode row in doc.SelectNodes(&quot;//RESPONSE/*[starts-with(name(),&#39;QUERY&#39;)]&quot;))
	{
		if(row.Attributes.Cast&lt;XmlAttribute&gt;().Any(x=&gt;x.Name==&quot;searched&quot;))
		{
			Result r2 = new Result(){
				SearchValue = row.Attributes[&quot;searched&quot;].Value,
				SearchResult = row.InnerText
			};
			r.Add(r2);
		}
	}

LINQ rewrite

	var nodes = doc.SelectNodes(&quot;//RESPONSE/*[starts-with(name(),&#39;QUERY&#39;)]&quot;)
					.Cast&lt;XmlNode&gt;();
					//.SelectMany(x=&gt;x.ChildNodes.Cast&lt;System.Xml.XmlElement&gt;());
	var query = (from elm in nodes
				where elm.Attributes.Cast&lt;XmlAttribute&gt;().Any(x=&gt;x.Name==&quot;searched&quot;)
				select new Result(){
					SearchValue = elm.Attributes[&quot;searched&quot;].Value,
					SearchResult = elm.InnerText
				}).ToList();

https://dotnetfiddle.net/RMxEiT

答案3

得分: 0

你可以将它转换成一个 JSON 对象并使用 Linq。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlResult);
var jObj = JObject.Parse(JsonConvert.SerializeXmlNode(xmlDoc));

List&lt;Result&gt; results = ((JObject)jObj[&quot;RESPONSE&quot;]).Properties()
               .Where(v =&gt; v.Name.StartsWith(&quot;QUERY&quot;))
               .Select(v =&gt; new Result
               {
                   SearchValue = (string)v.Value[&quot;@searched&quot;],
                   SearchResult = (string)v.Value[&quot;#text&quot;]
               }).ToList();
英文:

you can convert it to a json object and use Linq

	XmlDocument xmlDoc = new XmlDocument();
	xmlDoc.LoadXml(xmlResult);
	var jObj = JObject.Parse(JsonConvert.SerializeXmlNode(xmlDoc));

	List&lt;Result&gt; results = ((JObject)jObj[&quot;RESPONSE&quot;]).Properties()
			   .Where(v =&gt; v.Name.StartsWith(&quot;QUERY&quot;))
			   .Select(v =&gt; new Result
			   {
				   SearchValue = (string)v.Value[&quot;@searched&quot;],
				   SearchResult = (string)v.Value[&quot;#text&quot;]
			   }).ToList();

huangapple
  • 本文由 发表于 2023年3月31日 18:01:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定