C# 除了xml中的属性值外,还获取属性名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/416968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:35:47  来源:igfitidea点击:

get attribute name in addition to attribute value in xml

c#xml

提问by Greg J

I am receiving dynamic xml where I won't know the attribute names, if you'll look at the xml and code... I tried to make a simple example, I can get the attribute values i.e. "myName", "myNextAttribute", and "blah", but I can't get the attribute names i.e. "name", "nextAttribute", and "etc1". Any ideas, I figure it has to be something easy I'm missing...but I'm sure missing it.

我正在接收动态 xml,我不知道属性名称,如果您查看 xml 和代码...我试图举一个简单的例子,我可以获得属性值,即“myName”、“myNextAttribute” , 和“blah”,但我无法获得属性名称,即“name”、“nextAttribute”和“etc1”。任何想法,我认为它必须是我错过的一些简单的东西......但我肯定会错过它。

    static void Main(string[] args)
    {
        string xml = "<test name=\"myName\" nextAttribute=\"myNextAttribute\" etc1=\"blah\"/>";

        TextReader sr = new StringReader(xml);

        using (XmlReader xr = XmlReader.Create(sr))
        {
            while (xr.Read())
            {
                switch (xr.NodeType)
                {
                    case XmlNodeType.Element:
                        if (xr.HasAttributes)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                System.Windows.Forms.MessageBox.Show(xr.GetAttribute(i));
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

采纳答案by Dror

You can see in MSDN:

您可以在MSDN 中看到:

if (reader.HasAttributes) {
  Console.WriteLine("Attributes of <" + reader.Name + ">");
  while (reader.MoveToNextAttribute()) {
    Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
  }
  // Move the reader back to the element node.
  reader.MoveToElement();
}

回答by Soviut

Your switch is unnecessary since you only have a single case, try rolling that into your if statement instead.

您的 switch 是不必要的,因为您只有一个 case,请尝试将其滚动到 if 语句中。

if (xr.NodeType && xr.HasAttributes)
{
    ...
}

Note that the && operator evaluates in order, so if xr.NoteType is false, the rest of the arguments are ignored and the if block is skipped.

请注意 && 运算符按顺序计算,因此如果 xr.NoteType 为 false,则其余参数将被忽略并跳过 if 块。