无法提取XML文件中元素的属性值

问题描述 投票:0回答:1

我有一个XML模式文件,我正在尝试提取每个元素的属性值,即在此XM1模式文件(下面提到的文件)中。

您可能已经注意到,XML文件中大约有20个元素,因此,我正在寻找一种自动方法来从元素中提取数据,以避免手动工作。

对于每个元素,我需要以下属性值:类型,标签,CompType,只读,隐藏和必需。

例如,以下是XML文件中的一些元素:

<element type="xpowercomponent_FeaturedTiles" UID="40204fc9b5424b349e03134d777d29bc" label="Featured Tiles" readonly="false" hidden="false" default="" required="false" Component="" CompTypes="ThemedTileSetComponent;ThemedTileSetElectedComponent;" AutoEmbed="" WrappedUp="" AllowWrappingChange="" />

应该输出到控制台的预期结果将是:xpowercomponent_FeaturedTiles,精选图块,ThemedTileSetComponent,ThemedTileSetElectedComponent,readonly =“ false”,hidden =“ false”,需要= “假”

我已经创建了这个C#应用程序,尝试并实现了上面描述的内容,但是并没有给我想要的结果。我不确定逻辑是否正确,或者是否有更好的方法。

C#:

public static void Parse()
{    
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"D:\New Text Document.xml");

        var captureElements = new List<CustomElements>();
        var xdocument = xmlDoc.ToXDocument();
        foreach (var element in xdocument.Elements())
            foreach (var node in element.Elements()) //childs...
            {

                if (node.Name.LocalName.Equals("ElementType"))
                {
                    foreach (var scopeNode in node.Elements())
                    {
                        if (scopeNode.Name.LocalName.Equals("element"))
                        {
                            var xml = XElement.Parse(scopeNode.ToString());
                            var customElement = new CustomElements();

                            customElement.Type = xml.Attribute("type")?.Value;
                            customElement.Label = xml.Attribute("label")?.Value;
                            customElement.CompTypes = xml.Attribute("CompTypes")?.Value;
                            customElement.Readonly = xml.Attribute("readonly")?.Value;
                            customElement.Hidden = xml.Attribute("hidden")?.Value;
                            customElement.Require = xml.Attribute("required")?.Value;

                            captureElements.Add(customElement);  
                        }

                    }
                }
            }
        }
    }
}
public static class DocumentExtensions
{
    public static XmlDocument ToXmlDocument(this XDocument xDocument)
    {
        var xmlDocument = new XmlDocument();
        using (var xmlReader = xDocument.CreateReader())
        {
            xmlDocument.Load(xmlReader);
        }
        return xmlDocument;
    }

    public static XDocument ToXDocument(this XmlDocument xmlDocument)
    {
        using (var nodeReader = new XmlNodeReader(xmlDocument))
        {
            nodeReader.MoveToContent();
            return XDocument.Load(nodeReader);
        }
    }
}
public class CustomElements
{
    public string Type { get; set; }
    public string Label { get; set; }
    public string CompTypes { get; set; }
    public string Readonly { get; set; }
    public string Hidden { get; set; }
    public string Require { get; set; }
}

完整的XML模式文件:

<Schema xmlns:dt="urn:schemas-microsoft-com:datatypes" name="TopTier" xmlns="urn:schemas-microsoft-com:xml-data">
  <AttributeType name="ID" dt:type="id" required="yes" />
  <AttributeType name="Name" dt:type="string" required="yes" />
  <AttributeType name="UniqueID" dt:type="int" default="schemas/107" />
  <AttributeType name="Icon" dt:type="int" default="2" />
  <AttributeType name="FriendlyName" dt:type="string" default="Top Tier" />
  <AttributeType name="SS" dt:type="boolean" default="true" />
  <AttributeType name="DSS" dt:type="boolean" default="true" />
  <AttributeType name="ViewName" dt:type="" default="" />
  <AttributeType name="DefaultCategorization" dt:type="string" default="" />
  <AttributeType name="Version" dt:type="int" default="9" />
  <ElementType name="Exports" content="textOnly" />
  <ElementType name="Title" dt:type="string" content="textOnly" />
  <ElementType name="Excerpt" dt:type="string" content="textOnly">
    <description>This info is used to display on pages that link to this page.</description>
  </ElementType>
  <ElementType name="ThumbnailImage" dt:type="imagefile" content="textOnly">
    <description>Thumbnail dimension should be 75 x 75 pixels.</description>
  </ElementType>
  <ElementType name="xhtml_BodyCopy" content="textOnly" />
  <ElementType name="xpowerlist_LeftSidebarComponentsOverride" content="eltOnly" />
  <ElementType name="xpowercomponent_LeftSidebarComponent" content="eltOnly" />
  <ElementType name="xpowercomponent_FeaturedTiles" content="eltOnly" />
  <ElementType name="SecondaryTitle" dt:type="string" content="textOnly" />
  <ElementType name="xpowerlist_SecondaryComponentList" content="eltOnly" />
  <ElementType name="xpowercomponent_SecondaryItem" content="eltOnly" />
  <ElementType name="xpowergroupstart_SEOGroup" content="eltOnly">
    <description>Search Engine Optimization Group</description>
  </ElementType>
  <ElementType name="BrowserTitle" dt:type="string" content="textOnly" />
  <ElementType name="MetaDescription" dt:type="string" content="textOnly" />
  <ElementType name="NoIndex" dt:type="boolean" content="textOnly" />
  <ElementType name="NoFollow" dt:type="boolean" content="textOnly" />
  <ElementType name="NoODP" dt:type="boolean" content="textOnly" />
  <ElementType name="Priority" dt:type="enumeration" values="0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" content="textOnly" />
  <ElementType name="PublishDate" dt:type="localdate" content="textOnly" />
  <ElementType name="xpowergroupend_" content="eltOnly" />
  <ElementType name="xpowernavigation_BreadcrumbNavigation" content="eltOnly" />
  <ElementType name="xpowercomponent_SectionControl" content="eltOnly" />
  <ElementType name="TopTier" content="eltOnly" order="seq">
    <attribute type="ID" />
    <attribute type="Name" />
    <element type="Title" UID="2bbcb2816ba743e2bd935d526f47d688" label="Title" readonly="false" hidden="false" default="" required="true" />
    <element type="Excerpt" UID="2ac3ade7d9c34cae8a7f304d9754db86" label="Excerpt" readonly="false" hidden="false" default="" required="true" />
    <element type="ThumbnailImage" UID="f4940dbfe27f4783a97c356f3ba0f959" label="Thumbnail Image" readonly="false" hidden="false" default="" required="false" Expanded="false" Width="" Height="" Border="" HSpace="" VSpace="" Alignment="" AlternateText="" />
    <element type="xhtml_BodyCopy" UID="055d4709ffb24402a14f9d13af417401" label="Body Copy" readonly="false" hidden="false" default="" required="false" Height="" />
    <element type="xpowerlist_LeftSidebarComponentsOverride" UID="1d281fa780b6419089c52913640ade93" label="Left Sidebar Components Override" readonly="false" hidden="false" default="" required="false" Enclosed="" AllowEnclosureChange="" List="xpowercomponent_LeftSidebarComponent" Component="" CompTypes="" AutoEmbed="" WrappedUp="" AllowWrappingChange="" />
    <element type="xpowercomponent_FeaturedTiles" UID="40204fc9b5424b349e03134d777d29bc" label="Featured Tiles" readonly="false" hidden="false" default="" required="false" Component="" CompTypes="ThemedTileSetComponent;ThemedTileSetElectedComponent;" AutoEmbed="" WrappedUp="" AllowWrappingChange="" />
    <element type="SecondaryTitle" UID="3d00fbe341ff4f2481c6199deb046997" label="Secondary Title" readonly="false" hidden="false" default="" required="false" />
    <element type="xpowerlist_SecondaryComponentList" UID="3bc6293a826a4f2081dca1c5e1415978" label="Secondary Component List" readonly="false" hidden="false" default="" required="false" Enclosed="" AllowEnclosureChange="" List="xpowercomponent_SecondaryItem" Component="" CompTypes="TaxonomyTileComponent;ServiceComponent;ContactComponent;TitledCollection" AutoEmbed="" WrappedUp="" AllowWrappingChange="" />
    <element type="xpowergroupstart_SEOGroup" UID="bf312bbd47d74c758d13695b8fa011c0" label="SEO Group" readonly="false" hidden="true" default="" required="false" Enclosed="" AllowEnclosureChange="" />
    <element type="BrowserTitle" UID="c777f36e6f094b50a04692d3bfef387e" label="Browser Title" readonly="false" hidden="false" default="" required="false" />
    <element type="MetaDescription" UID="05bab416415541beb05e90b94f7e5248" label="Meta Description" readonly="false" hidden="false" default="" required="false" />
    <element type="NoIndex" UID="e224c1a3aaa846d9b19579d59d9b1af7" label="No Index" readonly="false" hidden="false" default="" required="false" />
    <element type="NoFollow" UID="b40ae068c0d749c4bb8ecd589388bb1b" label="No Follow" readonly="false" hidden="false" default="" required="false" />
    <element type="NoODP" UID="2557027d711d41c3b3ccbd3aab4650dd" label="No ODP" readonly="false" hidden="false" default="" required="false" />
    <element type="Priority" UID="f49eec4e94864e03aedbd0e2be6a2822" label="Priority" readonly="false" hidden="false" default="" required="false" values="0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0" />
    <element type="PublishDate" UID="5fdba65915744addb710631476822112" label="Publish Date" readonly="true" hidden="true" default="" required="false" />
    <element type="xpowergroupend_" />
    <element type="xpowernavigation_BreadcrumbNavigation" UID="140b1582e50e4a098e190942980bd728" label="Breadcrumb Navigation" readonly="false" hidden="true" default="" required="true" Expanded="false" Navigation="Ancestors" GenerationOrder="down" StartPage="x5" MaxNodes="" MaxDepth="" Query="">
      <element type="Exports" default="" />
    </element>
    <element type="xpowercomponent_SectionControl" UID="56564fa9c2bd4e9ba44a417960146376" label="SectionControl" readonly="false" hidden="true" default="" required="true" Component="" CompTypes="SectionControl" AutoEmbed="" WrappedUp="" AllowWrappingChange="" />
  </ElementType>
</Schema>
c# xml linq xml-parsing
1个回答
0
投票

尝试嵌套词典:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            XElement TopTier = doc.Descendants(ns + "ElementType").Where(x => (string)x.Attribute("name") == "TopTier").FirstOrDefault();

            Dictionary<string, Dictionary<string, string>> dict = TopTier.Elements(ns + "element")
                .GroupBy(x => (string)x.Attribute("type"), y => y.Attributes().Skip(1)
                    .GroupBy(a => a.Name.LocalName, b => (string)b)
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.