ASP.NET Tutorial/XML/XmlNode

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Display data in XML file recursively (VB.net)

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Xml" %>
<script runat=server>
   sub Page_Load(Sender as Object, e as EventArgs)
      dim xmldoc as new XMLDocument()
         
      xmldoc.Load(Server.MapPath("Data.xml"))
      ShowTree(xmldoc.DocumentElement)
      
   end sub
   
   sub ShowTree(node as XMLNode)
      Dim attrnode As XmlNode
      Dim map As XmlNamedNodeMap
    
      If Not(node.HasChildNodes)
         output.Text += "<b>" & node.Name & "</b> &lt;" & _
            node.Value & "&gt;<br>" & vbcrlf
      Else
         output.Text += "<b>" & node.Name & "</b>"
         If node.NodeType = XmlNodeType.Element Then
            map = node.Attributes
            For Each attrnode In map
               output.Text += " <b>" & attrnode.Name & "</b> &lt;" & _
                  attrnode.Value & "&gt; " & vbcrlf
            Next
         End If
         output.Text += "<br>"
      End If
      
      If node.HasChildNodes then
         node = node.FirstChild
         While not IsNothing(node)
            ShowTree(node)
            node = node.NextSibling
         end while
      end if
   end sub
</script>
<html><body>
   <asp:Label id="output" runat="server" />
</body></html>
File: Data.xml
<?xml version="1.0"?>
<bookstore>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
</bookstore>


Load data from XML

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="HolmesQuote" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
public partial class HolmesQuote : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    MyQuote quotes = new MyQuote(Server.MapPath("./Data.xml"));
    Quotation quote = quotes.GetRandomQuote();
    Response.Write("<b>" + quote.Source + "</b> (<i>" + quote.Date + "</i>)");
    Response.Write("<blockquote>" + quote.QuotationText + "</blockquote>");
      
  }
}
public class Quotation
{
  private string qsource;
  private string date;
  private string quotation;
  
  public Quotation(XmlNode quoteNode)
  {
    if ( (quoteNode.SelectSingleNode("source")) != null)
      qsource = quoteNode.SelectSingleNode("source").InnerText;
    if ( (quoteNode.Attributes.GetNamedItem("date")) != null)
      date = quoteNode.Attributes.GetNamedItem("date").Value;
    quotation = quoteNode.FirstChild.InnerText;
  }
  public string Source
  {
    get 
    {
      return qsource;
    }
    set 
    {
      qsource = value;
    }
  }
  public string Date
  {
    get 
    {
      return date;
    }
    set 
    {
      date = value;
    }
  }
  public string QuotationText
  {
    get 
    {
      return quotation;
    }
    set 
    {
      quotation = value;
    }
  }
}
public class MyQuote
{
  private XmlDocument quoteDoc;
  private int quoteCount;
  public MyQuote(string fileName)
  {
    quoteDoc = new XmlDocument();
    quoteDoc.Load(fileName);
    quoteCount = quoteDoc.DocumentElement.ChildNodes.Count;
  }
  public Quotation GetRandomQuote()
  {
    int i;
    Random x = new Random();
    i = x.Next(quoteCount-1);
    return new Quotation( quoteDoc.DocumentElement.ChildNodes[i] );
  }
}
File: Data.xml
<?xml version="1.0"?>
<quotations>
  <quotation date="1887">
    <pre>A</pre>
    <source>W
 </quotation>
 <quotation date="1887">
t
S
 </quotation>

</quotations></source>


MoveToNextAttribute

<%@ import Namespace="System" %>
<%@ import Namespace="System.Xml" %>
<%@ Page Language="C#" %>
<script runat="server">
    XmlTextReader _Reader; 
    
    public void Page_Load(Object Source, EventArgs E)
    {
        try{
            _Reader = new XmlTextReader(Server.MapPath("Data.xml"));
            ReadDocument(_Reader);
        }
        catch (Exception _Error){
            ErrorLabel.Text = _Error.Message;
        }
        finally{
            _Reader.Close();
        }
    
    }
    
    
    public void ReadDocument(XmlTextReader _XmlReader)
    {
      System.Text.StringBuilder sb = new System.Text.StringBuilder(100);
    String space3 = "&nbsp;&nbsp;&nbsp;";
    String space = "&nbsp;";
        while (_XmlReader.Read())
        {
            switch(_XmlReader.NodeType)
            {
              case XmlNodeType.Element:
                  sb.Append("<B>Element: </B>");
                  sb.Append(_XmlReader.Name);
                  sb.Append("<BR/>");
              
                  if (_XmlReader.AttributeCount > 0)
                  {
                      while (_XmlReader.MoveToNextAttribute())
                      {
                         sb.Append(space3);
                         sb.Append("<B>Attribute Name: </B>");
                         sb.Append(_XmlReader.Name);
                         sb.Append(space);
                         sb.Append("<B>Attribute Value: </B>");
                         sb.Append(_XmlReader.Value);
                         sb.Append("<BR/>");
                      }
                  }
              break;
    
              case XmlNodeType.Text:
                  sb.Append(space3);
                  sb.Append("<B>Value: </B>");
                  sb.Append(_XmlReader.Value);
                  sb.Append("<BR/>");
              break;
            }
        }
    OutputLiteral.Text = sb.ToString();   
    }
</script>
<html>
  <head>
    <title>Using the XmlTextReader</title>
  </head>
  <body>
    <form runat="server">
      
        <asp:Literal id="OutputLiteral" runat="server" EnableViewState="False"></asp:Literal>
      
      
        <asp:Label id="ErrorLabel" runat="server" ForeColor="Red"></asp:Label>
      
    </form>
  </body>
</html>