使用LINQ从XML文件读取

时间:2014-09-14 16:02:38

标签: c# xml linq

我正在尝试从XML文件中读取并将信息保存到字典中。

这就是我的XML的样子:

<?xml version="1.0" encoding="utf-8" ?>
<testUI_root>

  <!--Information for the first coded UI Test-->
  <codedUITest name ="CodedUITestMethod1">

    <description name ="Entering username from CSV" key = "1"/>
    <description name ="Entering password from CSV" key = "2"/>
    <description name ="Clicking exit" key ="3"/>

  </codedUITest>


</testUI_root>

所以我试着阅读并保存到词典中,这就是我尝试过的方法:

            //Load xml
            //StringBuilder description = new StringBuilder();
            int key;
            Dictionary<int, string> valDic = new Dictionary<int, string>();
            XDocument xdoc = XDocument.Load("XMLFile1.xml");


            //Run query
            var lv1s = from lv1 in xdoc.Descendants("codedUITest")
                       where lv1.Attribute("name").Value.Contains("CodedUITestMethod1")
                       select new
                       {
                           key = lv1.Descendants("key"),
                           value = lv1.Descendants("name")
                       };
            //loop
            foreach (var lv1 in lv1s)
            {
                foreach (var lv2_k in lv1.key)
                {
                   //it's not entering into this loop
                    foreach (var lv2_v in lv1.value)
                    {
                        // isn't entering here either
                        key = Convert.ToInt32(lv2_k.Attribute("key").ToString());
                        valDic.Add(key, lv2_v.Attribute("name").ToString());
                    }
                }
            }

            foreach (KeyValuePair<int, string> abc in valDic)
            {
                MessageBox.Show("Value: " + abc.ToString());
            }

没有语法错误,它是一个逻辑错误。 所以这就是我的字典应该是这样的。

/*
1.Entering Username from CSV
2.Entering password from CSV
3.Clicking exit
*/

将xml保存到输出目录。 (来自vs) 在LinqPad中尝试了代码,&#34;查询成功&#34;但没有输出。 我对Linq几乎没有任何经验,如果这个问题/错误是一个简单的问题,我会事先道歉。 感谢

2 个答案:

答案 0 :(得分:1)

您正在寻找ToDictionary方法

xdoc.Descendants("codedUITest")
.Where(x => x.Attribute("name").Value.Contains("CodedUITestMethod1"))
.Elements("description")
.ToDictionary(x => (int)x.Attribute("key"), x => (string)x.Attribute("name"));

答案 1 :(得分:-1)

使用XML序列化。使用visual studio附带的xsd.exe,您可以将XML代码表示为以下c#业务对象:

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class testUI_root {

    private testUI_rootCodedUITest[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("codedUITest", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public testUI_rootCodedUITest[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class testUI_rootCodedUITest {

    private testUI_rootCodedUITestDescription[] descriptionField;

    private string nameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("description", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public testUI_rootCodedUITestDescription[] description {
        get {
            return this.descriptionField;
        }
        set {
            this.descriptionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class testUI_rootCodedUITestDescription {

    private string nameField;

    private string keyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string key {
        get {
            return this.keyField;
        }
        set {
            this.keyField = value;
        }
    }
}

然后从那里,您可以将XML读入业务对象:

testUI_root theReturn = null;
System.Xml.Serialization.XmlSerializer s = null;
using (System.IO.FileStream fs = new System.IO.FileStream(thePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
    if (fs.Length > 0) {
        using (System.Xml.XmlTextReader r = new XmlTextReader(fs)) {
            s = new System.Xml.Serialization.XmlSerializer(typeof(testUI_root));
            theReturn = (testUI_root)s.Deserialize(r);
        }
    }
}
return theReturn;

并且您有XML的业务对象表示!从那里开始,使用链接搜索对象以查找所需的值应该非常容易。这只是对如何做你想做的事情的快速模拟,所以我还没有对它进行测试,但希望它能引导你走上正确的道路。