Search code examples
c#xmlxml-parsinglinq-to-xmlxelement

Get value between xml tags having a "title" as value in name attribute?


I'm currently importing webparts using a file upload control containing collection of webPartDescription (XML)

<wrapper>
  <webParts>
    <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
      <metaData>
        <type src="~/Web/Controls/Test/TestHeaderList.ascx" />
        <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
      </metaData>
      <data>
        <properties>
          <property name="UserCancelled" type="bool">False</property>
          <property name="AllowedRoles" type="string" null="true" />
          <property name="SourceFileName" type="bool">False</property>
          <property name="ViewFilterExpression" type="string" />
          <property name="UserCreated" type="bool">False</property>
          <property name="HideExportButtons" type="bool">False</property>
          <property name="RecordCount" type="bool">False</property>
          <property name="TransferStatus" type="bool">False</property>
          <property name="OrdersHeaderID" type="bool">False</property>
          <property name="TransmitRecordCount" type="bool">False</property>
          <property name="DataSource" type="Lobas.Demo.Web.Controls.Test+Views, Test.Demo.Web, Version=2.2.0.0, Culture=neutral, PublicKeyToken=null">None</property>
          <property name="DeltaCount" type="bool">False</property>
          <property name="OrdersHeaderBatchNo" type="bool">False</property>
          <property name="DateCancelled" type="bool">False</property>
          <property name="ResponseDescription" type="bool">False</property>
          <property name="RunDate" type="bool">False</property>
          <property name="DateCreated" type="bool">False</property>
          <property name="ResponseCode" type="bool">False</property>
        </properties>
        <genericWebPartProperties>
          <property name="Width" type="unit" />
          <property name="Description" type="string" />
          <property name="AllowEdit" type="bool">True</property>
          <property name="ChromeType" type="chrometype">Default</property>
          <property name="TitleIconImageUrl" type="string" />
          <property name="Hidden" type="bool">False</property>
          <property name="TitleUrl" type="string" />
          <property name="AllowClose" type="bool">True</property>
          <property name="AllowMinimize" type="bool">True</property>
          <property name="AllowConnect" type="bool">True</property>
          <property name="Height" type="unit" />
          <property name="HelpMode" type="helpmode">Navigate</property>
          <property name="Title" type="string">Orders Header List</property>
          <property name="CatalogIconImageUrl" type="string" />
          <property name="Direction" type="direction">NotSet</property>
          <property name="AllowZoneChange" type="bool">True</property>
          <property name="ChromeState" type="chromestate">Normal</property>
          <property name="HelpUrl" type="string" />
          <property name="AllowHide" type="bool">True</property>
          <property name="ExportMode" type="exportmode">NonSensitiveData</property>
        </genericWebPartProperties>
      </data>
    </webPart>
  </webParts>
</wrapper>

i want to filter and fetch the value of property element inside "genericWebPartProperties" with attribute name ="Title" eg : Orders Header List (in above xml)

i'm new to linq and xml. i tried several solutions but received null

My code behind looks like :

//Uploded xml containing multible webparts wraped under <wrapepr> root tag.
XDocument UploadedXmlWebparts = XDocument.Load(e.UploadedFile.FileContent);

// fetching individual webpart xml and storing in a Xelement Collection
                var WebpartCollection = UploadedXmlWebparts.Root.Elements();
                List<ClsImportWp> WebPartDescriptionList = new List<ClsImportWp>();

                foreach (XElement webPart in WebpartCollection)
                {
                   var TitleName = // Get the title tag value here 
                }

Solution

  • Use xml linq with a dictionary :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication166
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                XElement genericWebPartProperties = doc.Descendants().Where(x => x.Name.LocalName == "genericWebPartProperties").FirstOrDefault();
                XNamespace ns = genericWebPartProperties.GetDefaultNamespace();
                Dictionary<string,string> dict = genericWebPartProperties.Elements(ns + "property")
                    .GroupBy(x => (string)x.Attribute("name"), y => (string)y)
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
     
            }
        }
    
    }