【问题标题】:get attribute name in addition to attribute value in xml获取xml中除了属性值之外的属性名称
【发布时间】:2009-01-06 15:30:31
【问题描述】:

我正在接收动态 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;
                }
            }
        }
    }

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    你可以在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();
    }
    

    【讨论】:

    • 谢谢,我认为它必须是接近的东西......我也在我原来的 for 循环中发现,我可以完成 xr.MoveToAttribute(i) 并获得相同的效果。
    【解决方案2】:

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

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

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

    【讨论】:

    • 在这个例子中,是的,我在“现实世界”场景中有更多案例,我只是试图保持干净。不过还是谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2011-10-02
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多