Напишите XML, используя лучший способ (Linq To XML или другой)

Я хочу написать свой xml в следующем формате. Как я могу это сделать? Я использую c #

<map borderColor='c5e5b8' fillColor='6a9057' numberSuffix=' Mill.' includeValueInLabels='0' labelSepChar=': ' baseFontSize='9' showFCMenuItem='0'
hoverColor='c2bc23' showTitle='0' type='0' showCanvasBorder='0' bgAlpha='0,0' hoveronEmpty='1' includeNameInLabels='0' showLabels='1'>
<!--toolText='Alaska'imageSave='1' imageSaveURL='Path/FusionChartsSave.aspx or FusionChartsSave.php'-->
<data>
<entity id='AL' value='AL' link="JavaScript:FilterClientProjectList('AL');" fontBold='1' showLabel='0' />
<entity id='AK' value='AK' link="JavaScript:FilterClientProjectList('AK');" fontBold='1' hoverColor='6a9057'/>
<entity id='AZ' value='AZ' link="JavaScript:FilterClientProjectList('AZ');" fontBold='1'/>
</data>

<styles>
<definition>
<style name='MyFirstFontStyle' type='font' face='Verdana' size='11' color='0372AB' bold='1' bgColor='FFFFFF' />
</definition>
<application>
 <apply toObject='Labels' styles='' />
</application>
</styles>
</map>

Заранее спасибо..


person Pankaj    schedule 08.03.2010    source источник


Ответы (3)


Я бы использовал LINQ to SQL (mydatasource предполагал SQL), затем LINQ to XML, а затем XSLT, чтобы получить точный XML, который вы ищете.

Вот пример: Мой XML

<Promotions> 
      <Promotion> 
        <Category>Arts &amp; Entertainment</Category> 
        <Client>Client 1</Client> 
        <ID>2</ID> 
        <Title>Get your Free 2</Title> 
      </Promotion> 
      <Promotion> 
        <Category>Community &amp; Neighborhood</Category> 
        <Client>Client1</Client> 
        <ID>4</ID> 
        <Title>Get your Free 4</Title> 
      </Promotion> 
      <Promotion> 
        <Category>Community &amp; Neighborhood</Category> 
        <Client>Client 1</Client> 
        <ID>5</ID> 
        <Title>Get your Free 5</Title> 
      </Promotion> 
      <Promotion> 
        <Category>Community &amp; Neighborhood</Category> 
        <Client>Client 2</Client> 
        <ID>1</ID> 
        <Title>Get your Free 1</Title> 
      </Promotion> 
      <Promotion> 
        <Category>Education</Category> 
        <Client>Client 3</Client> 
        <ID>3</ID> 
        <Title>Get Your Free 3</Title> 
      </Promotion> 
      <Promotion> 
        <Category>Home &amp; Garden</Category> 
        <Client>Client 4</Client> 
        <ID>6</ID> 
        <Title>Get your Free 6</Title> 
      </Promotion> 
    </Promotions> 

Мой код:

 PromotionsDataContext db = new PromotionsDataContext();
                        //load sql into XML for tree view js control
                        XElement Categories =
                            new XElement("Promotions",
                                from b in db.Promotion_GetPromotions()
                                select new XElement("Promotion",
                                    new XElement("Category", b.CategoryName),
                                       new XElement("Client", b.ClientName),
                                       new XElement("ID", b.ID),
                                       new XElement("Title", b.Title)));

                        XDocument mydoc = new XDocument();
                        mydoc.Add(Categories);

                        try
                        {

                        // Load the style sheet.
                        XslCompiledTransform xslt = new XslCompiledTransform();
                        xslt.Load(@"C:\TransList.xslt");

                        // Execute the transform and output the results to a writer.
                        StringWriter sw = new StringWriter();
                        //XsltSettings mysettings = new XsltSettings();
                        XmlWriterSettings mysettings = new XmlWriterSettings();

                        xslt.Transform(mydoc.CreateReader(), null, sw);

Мой файл XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:asp="http://schemas.microsoft.com/ASPNET/20">


  <xsl:output method="html" indent="yes" />

  <xsl:key name="categories" match="Category" use="." />
  <xsl:key name="client" match="Client" use="." />
  <xsl:key name="title" match="Title" use="." />

  <xsl:template match="/">

    <ul id="red" class="treeview-red">
      <xsl:for-each select="/Promotions/Promotion/Category[  
                generate-id(.) = generate-id(key('categories', .)[1])  
                ]">
        <li>
          <span>
            <xsl:value-of select="."/>
            <!--Category-->
          </span>

          <ul>
            <xsl:call-template name="category-client">
              <xsl:with-param name="category" select="."/>
              <!--Client-->
            </xsl:call-template>
          </ul>
        </li>

      </xsl:for-each>
    </ul>

  </xsl:template>

  <xsl:template name="category-client">
    <xsl:param name="category" />
    <xsl:for-each select="/Promotions/Promotion[Category=$category]/Client[  
                generate-id(.) = generate-id(key('client', .)[1]) 
                ]">
      <li>
        <span>
          <xsl:value-of select="."/>
        </span>
        <ul>
          <xsl:call-template name="category-client-title">
            <xsl:with-param name="category" select="$category"/>
            <!--Title-->
            <xsl:with-param name="client" select="."/>
          </xsl:call-template>
        </ul>
      </li>
    </xsl:for-each>
  </xsl:template>

  <xsl:template name="category-client-title">
    <xsl:param name="category" />
    <xsl:param name="client" />
    <xsl:for-each select="/Promotions/Promotion[Category=$category]/Title[  
                generate-id(.) = generate-id(key('title', .)[1]) 
                ]">
      <li>
        <span>
          <asp:LinkButton ID ="LinkButton{../ID}" runat="server" OnClick="LinkClicked" Text="{.}">
          </asp:LinkButton>
        </span>
      </li>

    </xsl:for-each>

  </xsl:template>

</xsl:stylesheet>

Вот некоторые вещи, которые я обнаружил при работе с XSLT на C #:

Что я здесь делаю неправильно, имея проблемы с XSLT с использованием C #

Как получить в XSLT одноуровневого элемента по имени тега?

рендеринг XSLT и для ›‹ как мне это обойти?

person James Campbell    schedule 08.03.2010

Если у меня есть проект, который интенсивно работает с Xml, я всегда создаю проект VB. Вы можете объявить образец xml как:

Dim sampleXml = 
<Promotions> 
      <Promotion> 
        <Category>Arts &amp; Entertainment</Category> 
        <Client>Client 1</Client> 
        <ID>2</ID> 
        <Title>Get your Free 2</Title> 
      </Promotion> 
      <Promotion> 
        <Category>Client 1</Category> 
        <Client>Artsquest</Client> 
        <ID>4</ID> 
        <Title>Get your Free 4</Title> 
      </Promotion> 
      <Promotion> 
        <Category>Client 1</Category> 
        <Client>Artsquest</Client> 
        <ID>5</ID> 
        <Title>Get your Free 5</Title> 
      </Promotion> 
      (....)

и получить такой элемент, как:

Dim firstPromotion = sampleXml.Promotions.Promotion(0)

или что-то подобное.

Даже если у меня есть проект на C #, я создаю dll-проект VB для работы с xml. Это намного чище, чем то, что вам нужно делать на C # с помощью newXElement.

person Guillaume Hanique    schedule 09.03.2010