简体   繁体   中英

convert xml value to string (use c#)


in xml file

<dummy1>
  <dummy2>
    <dummy3>
      <items>
        <item id="1111" name="Real_item_Name" url="i=1111">
          <filter name="itemLevel" value="item_value"/>
          <filter name="source" value="dummy4"/>
        </item>
       <item id="2222" name="Real_item_Name2" url="i=222">
          <filter name="itemLevel" value="item_value2"/>
          <filter name="source" value="dummy5"/>
        </item>
              //roop 
      </items>
    </dummy3>
  </dummy2>
</dummy1>

how can i make this value in c# (insert String value)

Real_item_Name , 1111 , item_value
Real_item_Name2 , 2222 , item_value2
Real_item_Name3 , 3333 , item_value3

please show me dom or sax example ...

There's a dozen different ways to do this. Here's a very simple example using XSL :

mytransform.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <xsl:for-each select="items/item">
        <xsl:value-of select="@name" />, <xsl:value-of select="@id" />, <xsl:value-of select="filter/@value" />
    </xsl:for-each>
</xsl:template>

We load the XSL file into a transform object; specify an input XML and an output text file:

XslTransform xslt = new XslTransform();
xslt.Load("c:\\path\\mytransform.xsl");
xslt.Transform("c:\\path\\input.xml", "c:\\path\\output.txt");

Check out the documentation on XslTransform for more in-depth usage, like working in memory streams and XML objects instead of file paths. This demonstrates the core concepts though.

XDocument xml = XDocument.Load("foo.xml");
string csv = string.Join("\n",
    xml.Descendants("item").Select(item =>
        string.Format("{0}, {1}, {2}",
            (string)item.Attribute("name"),
            (string)item.Attribute("id"),
            (string)item.Elements("filter")
                        .Single(f => f.Attribute("name") == "itemLevel")
                        .Attribute("value")))
       .ToArray());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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