从列表中的C#中的XML文件中获取类型的值

时间:2015-09-08 07:19:53

标签: c# xml

我想从列表中的C#中获取XML值。有一些特定的条件,比如,我需要显示ruleid,dataprovider,在属性中我想得到名字, 在需要获得价值的条件(20),运营商(greaterthan或lessthan)类型="健康"。

示例XML。

"<psmsmanifiest version=\"2\" lastmodified=\"2015-08-06 03:53:06.207\">" +
              "<rules>" +
                "<!--sample for runtime data provider-->" +
                "<rule ruleid=\"8504dcad-f748-4add-9e95-239d5382f1c6\" dataprovider=\"runtime\">" +
                  "<attributes>" +
                    "<attribute name=\"platform.attibute1.value\" type=\"int\">" +
                      "<conditions>" +
                        "<condition type=\"healthy\" operator=\"greaterthan\">100></condition>" +
                        "<condition type=\"unhealthy\" operator=\"greaterthanequal\">100></condition>" +
                      "</conditions>" +
                    "</attribute>" +
                    "<attribute name=\"platform.attibute2.value\" type=\"int\">" +
                      "<conditions>" +
                        "<condition type=\"healthy\" operator=\"greaterthan\">100></condition>" +
                        "<condition type=\"unhealthy\" operator=\"greaterthanequal\">100></condition>" +
                      "</conditions>" +
                    "</attribute>" +
                  "</attributes>" +
                "</rule>" +
              "</rules>" +
            "</psmsmanifiest>

我尝试按以下方式解析数据:

public static void readXml()
    {
        XmlDocument xmldoc = new XmlDocument();
        XmlNodeList xmlnode;
        int i = 0;
        List<Rule> listx = new List<Rule>();

        FileStream fs = new FileStream("C://ConsoleApplication1//sample_manifest.xml", FileMode.Open, FileAccess.Read);
        xmldoc.Load(fs);
        xmlnode = xmldoc.GetElementsByTagName("attribute", "condition");
         XmlNodeList list = xmldoc.SelectNodes(@"/psmsmanifiest/rules/rule/attributes");

         foreach (XmlNode node in list)
        {
            foreach (XmlNode childNode in node.ChildNodes)
            {

                //string dataprovider = node["Dataprovider"].Attributes.Item(0);
                var attribute = node["attribute"].InnerXml;
                Console.WriteLine(attribute);
                Console.ReadLine();

         }
        }
    }

如何以简单和更好的方式实现?

1 个答案:

答案 0 :(得分:0)

当处理xml时,我通常会避免手动解析(除非xml不知道apriori)。您可以使用XSD.exe生成解析器。

  • 打开visual studio命令行。
  • (可选)(为方便起见),将目录更改为xml文件位置,以便在同一位置生成文件,而不是xsd.exe所在的位置。
  • 写&#39; xsd.exe&#39;从xml生成xsd文件。
  • 编写&#39; xsd / c以生成一个能够解析xml的C#类。
  • 在项目中导入.cs文件
  • 反序列化您的xml文件:

    XmlSerializer serializer = new XmlSerializer(typeof(YourType));
    StreamReader reader = new StreamReader(yourXmlPath);
    var yourStronglyTypedObject =(YourType)serializer.Deserialize(reader); reader.Close();

  • 使用强类型对象

  • 值得花1小时学习xsd:您可能需要稍微更改xsd以更好地反映您的xml格式。自动生成的xsd通常更通用,更宽松,例如。倾向于使用超过需要的集合(只需修复maxOccurs / minOccurs属性)

希望这有帮助。