【问题标题】:How to get all attribute names from selected XML node in C#如何从 C# 中的选定 XML 节点获取所有属性名称
【发布时间】:2017-01-10 08:34:42
【问题描述】:

这是我的 XML 文件。我需要选择一个测试元素并从其结果子节点中获取所有属性名称。

<?xml version="1.0" encoding="UTF-8"?>
<summary>
  <test>
    <id>test 1</id>   
    <result value="-45">330</result>
    <result value="0">300</result>
    <result value="45">340</result>
  </test>
  <test>
    <id>test 3</id>    
    <result value="-45">330</result>
    <result value="0">300</result>
    <result value="45">340</result>
  </test>
</summary>

我写了下面的代码。但重复相同的值,我想停止它。

XmlDocument xd = new XmlDocument();
xd.Load(_xmlFilePath);

XmlNodeList nodelist = xd.GetElementsByTagName("result");

foreach (XmlNode node in nodelist)
    {
        string attrVal = node.Attributes["value"].Value;
        Console.WriteLine(attrVal);
    }

欢迎提出任何建议。

谢谢。

【问题讨论】:

  • 你能显示nodelist的期望值和attrVal的输出吗
  • 输出应该是-45,0,45

标签: c# xml tags xmlreader


【解决方案1】:

您可以将 LINQ to Xml 与 XDocument 类一起使用

var doc = XDocument.Load(_xmlFilePath);

var distinctResults = doc.Descendants("result")
                         .Select(element => element.Attribute("value").Value)
                         .Distinct();

foreach(var result in distinctResults)
{
    Console.WriteLine(result);
}

或者使用HashSet&lt;string&gt;

var results = doc.Descendants("result")
                 .Select(element => element.Attribute("value").Value);

var distinctResults = new HashSet<string>(results); 

foreach(var result in distinctResults)
{
    Console.WriteLine(result);
}

【讨论】:

  • “System.Xml.XmlDocument”不包含“Descendants”的定义,并且找不到接受“System.Xml.XmlDocument”类型的第一个参数的扩展方法“Descendants”
  • 使用XDocument类代替XmlDocument
【解决方案2】:

尝试以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication34
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);

            string id = "test 1";

            var results = doc.Descendants("test").Where(x => (string)x.Element("id") == id).FirstOrDefault().Elements("result").Select(x => new
            {
                angle = (int)x.Attribute("value"),
                length = (int)x
            }).ToList();

        }


    }


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-29
    • 2019-10-02
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    相关资源
    最近更新 更多