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
get attribute name in addition to attribute value in 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
回答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 块。