繁体   English   中英

读取特定的XML元素

[英]Reading specific XML element

我们有一家供应商公司,要求xml数据文件具有特定的布局。 该结构在XSD文件中定义,并且该结构可以每月更新(发送新的XSD文件)(可以重新排列或删除元素)。

我有一个XML文件,但是我需要按照与XSD要求相同的顺序来排列元素。 下面是我的代码,可以读取XML文件。 根据我在这里的帖子,我能够遍历XSD文件。

我的问题是我无法从xml文件返回特定元素。 我怎样才能做到这一点?

        foreach (var XSDsection in sections)
        {
            //Get Section Element;
            string SchemaSchedule = XSDsection.Attribute("name").Value;
            var SchemaSectionSchedule = XSDsection.Element(prefix + "complexType")
                                .Element(prefix + "sequence")
                                .Elements(prefix + "element");
            foreach (var schemaSection in SchemaSectionSchedule)
            {
                //Get child element;
                string schemaElement = schemaSection.Attribute("name").Value;
                var XMLsectionSchedule = xDoc.Descendants(SchemaSchedule);

                foreach (XElement element in xDoc.Element(SchemaSchedule).Descendants())
                {
                    string value = element.Value;       //returns value of next element;
                    string el = element.ToString();     //returns the next element and value from xml file;
                }
            }
        }

我不是XML方面的佼佼者,但我认为您可以执行以下操作:

    foreach (var XSDsection in sections)
    {
        //Get Section Element;
        string SchemaSchedule = XSDsection.Attribute("name").Value;
        var SchemaSectionSchedule = XSDsection.Element(prefix + "complexType")
                            .Element(prefix + "sequence")
                            .Elements(prefix + "element");
        foreach (var schemaSection in SchemaSectionSchedule)
        {
            //Get child element;
            string schemaElement = schemaSection.Attribute("name").Value;
            var XMLsectionSchedule = xDoc.Descendants(SchemaSchedule);

            foreach (XElement element in xDoc.Element(SchemaSchedule).Descendants())
            {
                string value = element.Value;       //returns value of next element;
                string el = element.ToString();     //returns the next element and value from xml file;
                if(value == myDesiredValue)
                {
                    return element; // if you want the element, return it
                }
            }
        }
    }

请注意,这将返回仅匹配的第一个元素。 一旦找到它,它将返回该元素并停止循环遍历。

暂无
暂无

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

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