星期四, 9月 13, 2007

用C#讀取XML的元素和屬性

用C#讀取XML的元素和屬性

Method 1 (ex. Google Weather API)
private String weatherApiUri = @"http://www.google.co.uk/ig/api?weather=";
private String xmlNode = "xml_api_reply/weather/current_conditions";

XmlDocument xd = (XmlDocument)xmlFromGoogle; //set xml document
XmlNodeList xnl = xd.SelectNodes(xmlNode); //get the node

XmlNode xmlDetail;
xmlDetail = GWP_NodeList.Item(0).SelectSingleNode("condition ");
Console.write(xmlDetail.Attributes["data"].InnerText);


Method 2


using System.Xml;
namespace DOMTest
{
class DOM
{
private static void PrintElement(XmlDocument document)
{
//獲取所有的Node
XmlNodeList nodeList=document.GetElementsByTagName('*');
//打印每一個node的名稱
for (int i=0;i (less) nodeList.Count;i++)
{
XmlNode node=nodeList.Item(i);
Console.WriteLine(node.Name);
}
}

private static void PrintAttributes(XmlDocument document)
{
XmlNodeList nodeList=document.GetElementsByTagName("*");
XmlNamedNodeMap nameNodeMap;
XmlElement element;
XmlAttribute attribute;
string attributeName;
string attributeValue;

for(int i=0;i (less) nodeList.Count;i++)
{
element=(XmlElement)nodeList.Item(i);
Console.WriteLine(element.Name+":"+element.ChildNodes[0].Value);
nameNodeMap=element.Attributes;
if(nameNodeMap!=null)
{
for(int j=0;j (less) nameNodeMap.Count;j++)
{
attribute=(XmlAttribute)nameNodeMap.Item(j);
attributeName=attribute.Name;
attributeValue=attribute.Value;
Console.WriteLine("屬性是:"+attributeName+"="+attributeValue);
}
}
}
}
[STAThread]
static void Main(string[] args)
{
XmlDocument document =new XmlDocument();
document.Load("student.xml");
Console.WriteLine("元素是:");
PrintElement(document);

// Console.WriteLine("元素屬性是:");
// PrintAttributes(document);
}
}
}

沒有留言: