繁体   English   中英

使用LINQ从XML文件读取

[英]Reading from a XML file with 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中的代码,“查询成功”,但没有输出。 我对Linq几乎没有任何经验,如果这个问题/错误很简单,我先向您道歉。 谢谢

您正在寻找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"));

而是使用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的业务对象表示! 从那里开始,应该很容易使用链接搜索对象以找到所需的值。 这只是如何做自己想做的事的快速模拟,因此我尚未进行测试,但希望它将引导您走上正确的道路。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM