简体   繁体   English

如何访问某个元素并检索数据XML

[英]How to access a certain element and retrieve the data XML

My XML looks like this. 我的XML看起来像这样。 I can contain n numbers of modules and n number of assignments. 我可以包含n个模块和n个分配。 The assignments are nested in the modules that it contains: 分配嵌套在它包含的模块中:

<?xml version="1.0"?>
<Course name="engineering">
<Level4>
    <Module Name="electric" CreditVal="22">
        <Assignment Name="wer" Score="22" Weight="50">
        </Assignment>
        <Assignment Name="asd" Score="50" Weight="50">
        </Assignment>
    </Module>
    <Module Name="materials" CreditVal="22">
        <Assignment Name="ghj" Score="22" Weight="75>
        </Assignment>
        <Assignment Name="kl" Score="80" Weight="15">
        </Assignment>
    </Module>
</Level4>
</Course>

I am accessing the modules and assignments by the following: 我通过以下方式访问模块和分配:

XPathDocument xpd = new XPathDocument("XMLFile.xml");

//getting modules in level 4
foreach (XPathNavigator mod in xpd.CreateNavigator().Select("/Course/Level4/Module"))
{
    //Accessing module elemtns
    if (mod.HasAttributes)
    {
        Module modtoadd = new Module();
        modtoadd.Name = mod.GetAttribute("Name", "");
        Console.WriteLine("module name: " + modtoadd.Name);
        modtoadd.CreditValue = int.Parse(mod.GetAttribute("CreditVal", ""));
        Console.WriteLine("module cred: " + modtoadd.CreditValue);
        modtoadd.Assignments = new List<Assignment>();
        //Accessing assignment elements within the module element
        foreach (XPathNavigator asgn in xpd.CreateNavigator().Select("Course/Level4/Module/Assignment"))
        {
            Assignment asn = new Assignment();
            asn.Name = asgn.GetAttribute("Name", "");
            Console.WriteLine(asn.Name);
            asn.Weighting = int.Parse(asgn.GetAttribute("Weight", ""));
            Console.WriteLine(asn.Weighting);
            asn.UsersScore = int.Parse(asgn.GetAttribute("Score", ""));
            Console.WriteLine(asn.UsersScore);
            modtoadd.Assignments.Add(asn);
        };
        courseXML.Level_41.Add(modtoadd);
    }
};

What is supposed to happen: The xmlreader reads the assignment nested in the relative modules it resides in. Eg if I were to total up the module score then 'eletric' should be worth 72 and 'materials' should be worth 102. 应该发生的情况:xmlreader读取嵌套在其所驻留的相对模块中的分配。例如,如果我对模块得分进行总计,那么“ eletric”应该值72,而“ materials”值102。

What actually happens: After testing it I realised there is something wrong with the logic. 实际发生的情况:经过测试,我意识到逻辑上有问题。 This works fine when one module is saved but if there is more than one then ALL the assignments will be added the every module. 当保存一个模块时,此方法效果很好,但是如果有多个模块,则所有分配都将添加到每个模块中。 If I were to total up the module score then materials and electric are both worth 174. 如果我将模块总分加起来,那么材料和电都值174。

I am new to XML and reading/saveing to files. 我是XML和读取/保存文件的新手。 Thanks for the help :) 谢谢您的帮助 :)

I always find Linq2Xml easier to use. 我总是觉得Linq2Xml更易于使用。

var xDoc = XDocument.Load(filename);
var res  = xDoc.Descendants("Module")
            .Select(m => new
            {
                Name = (string)m.Attribute("Name"),
                CreditVal = (int)m.Attribute("CreditVal"),

                Assignments = m.Descendants("Assignment")
                                .Select(a => new
                                {
                                    Name = (string)a.Attribute("Name"),
                                    Score = (int)a.Attribute("Score"),
                                    Weight = (int)a.Attribute("Weight")
                                })
                                .ToList()
            })
            .ToList();

The problem is that instead of reading the Assignment neated under the current mod , you are reading from every Assignment from the document. 问题是,而不是读取Assignment下的电流neated mod ,你是从每一个阅读Assignment从文档。

//foreach (XPathNavigator asgn in xpd.CreateNavigator().Select("Course/Level4/Module/Assignment"))
foreach (XPathNavigator asgn in mod.CreateNavigator().Select("Assignment"))

However, consider using the solution provided by @Eser. 但是,请考虑使用@Eser提供的解决方案。 It is must simpler than your approach. 它必须比您的方法简单。

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

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