<?xml version="1.0"?>
<aws:UrlInfoResponse xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/">
 <aws:Response xmlns:aws="http://awis.amazonaws.com/doc/2005-07-11">
  <aws:UrlInfoResult>
<aws:Alexa>
<aws:ContactInfo>
<aws:Email>baidu_dns_master@baidu.com</aws:Email>
</aws:ContactInfo>
<aws:Alexa>
  </aws:UrlInfoResult>
 </aws:Response>
</aws:UrlInfoResponse>
假如你要取得<aws:Email>节点,诶,你发现<aws:UrlInfoResponse>和<aws:Response>节点的命名空间马甲是一样的。
这个时候怎么办呢?难道是添加两次aws命名空间?其实不然。做法如下:
1.我们只要添加<aws:Response>节点的命名空间。
xnm.AddNamespace("aws", "http://awis.amazonaws.com/doc/2005-07-11");
2.取得根节点,这样我们就可以忽略根结点的命名空间,然后应用XPath取得你想要的节点。
XmlElement xe = xd.DocumentElement;
XmlNodeList xnl = xe.SelectNodes(
"//aws:Response/aws:UrlInfoResult/aws:Alexa/aws:ContactInfo/aws:Email", xnm);
直接这样取好像也可以:
XmlNodeList xnl = xd.SelectNodes(
"//aws:Response/aws:UrlInfoResult/aws:Alexa/aws:ContactInfo/aws:Email", xnm);
这样我们就可以得到<aws:Email>节点了,然后打印出来
foreach (XmlNode xn1 in xnl)
{
Response.Write(xn1.InnerXml.ToString() + "</br>");
}
完整代码:
XmlDocument xd = new XmlDocument();
xd.Load(Server.MapPath(".")+"/a.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(xd.NameTable);
xnm.AddNamespace("aws", "http://awis.amazonaws.com/doc/2005-07-11");
XmlElement xe = xd.DocumentElement;
XmlNodeList xnl = xe.SelectNodes(
"//aws:Response/aws:UrlInfoResult/aws:Alexa/aws:ContactInfo/aws:Email", xnm);
//XmlNodeList xnl = xd.SelectNodes(
//"//aws:Response/aws:UrlInfoResult/aws:Alexa/aws:ContactInfo/aws:Email", xnm);
foreach (XmlNode xn1 in xnl)
{
Response.Write(xn1.InnerXml.ToString() + "</br>");
}
--------------------------------------------------------
譬如要讀到DataSet中,如:

               XmlDocument doc = new XmlDocument();
                doc.Load(filename);
                XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
                xnm.AddNamespace("s", "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882");
                xnm.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");

                XmlNode node = doc.SelectSingleNode("//xml/rs:data", xnm);
                XmlNodeReader reader = new XmlNodeReader(node);
                ds.ReadXml(reader);

posted on 2008-11-17 09:26  fmxyw  阅读(588)  评论(0编辑  收藏  举报