我有一个类似的xml的 string,想通过遍历怎么个xml 输出我想要的element的值xml 为:<Discover xmlns="urn:schemas-microsoft-com:xml-analysis">
  <RequestType>DISCOVER_XML_METADATA</RequestType>
  <Restrictions>
    <RestrictionList>
      <ObjectExpansion>ObjectProperties</ObjectExpansion>
    </RestrictionList>
  </Restrictions>
  <Properties>
    <PropertyList>
    </PropertyList>
  </Properties>
</Discover>
我现在通过遍历,先判断是否有 ObjectExpansion 节点,如果有输出其值。请指教。

解决方案 »

  1.   

    // XML 读取XML文件中的元素和元素属性
    private static void PrintElement(XmlDocument document)
    {
        XmlNodeList nodeList = document.GetElementsByTagName("*");  //获取所有的Node
        for (int i = 0; i < nodeList.Count; i++)
        {
            XmlNode node = nodeList.Item(i);
            MessageBox.Show(node.Name);                           //打印每一个node的名称
        }
    }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 < nodeList.Count; i++)
        {
            element = (XmlElement)nodeList.Item(i);
            MessageBox.Show(element.Name + ":" + element.ChildNodes[0].Value);
            nameNodeMap = element.Attributes;
            if (nameNodeMap != null)
            {
                for (int j = 0; j < nameNodeMap.Count; j++)
                {
                    attribute = (XmlAttribute)nameNodeMap.Item(j);
                    attributeName = attribute.Name;
                    attributeValue = attribute.Value;
                    MessageBox.Show("属性是:" + attributeName + "=" + attributeValue);
                }
            }
        }
    }// 测试用例
    private void button4_Click(object sender, EventArgs e)
    {
        XmlDocument document = new XmlDocument();
        document.Load("c:\\student.xml");
        Console.WriteLine("元素是:");
        PrintElement(document);    Console.WriteLine("元素属性是:");
        PrintAttributes(document);
    }
      

  2.   

    /// <summary>
            /// 根据节点名读出相应的节点内容
            /// </summary>
            /// <param name="parentname"></param>
            /// <param name="subname"></param>
            /// <returns></returns>
            public static string GetNode(string filepath,string parentname,string subname)
            {
                string _NodeValue=string.Empty;
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filepath);
                XmlNodeList nodeList = xmlDoc.SelectSingleNode("Config_Cache").ChildNodes;            
                
                foreach (XmlNode xn in nodeList)
                {                
                    XmlElement xe = (XmlElement)xn;
                    if (xe.GetAttribute("genre") == parentname)
                    {
                        XmlNodeList nls = xe.ChildNodes;
                        foreach (XmlNode xnl in nls)
                        {
                            XmlElement xe2 = (XmlElement)xnl;
                            if (xe2.Name.ToLower() == subname.ToLower())
                            {
                                _NodeValue = xe2.InnerXml;
                                break;
                            }
                        }
                    }
                }
                return _NodeValue;
            }
    /// <summary>
            /// 将xml文件转换为DataSet
            /// </summary>
            /// <param name="xmlFile"></param>
            /// <returns></returns>
            public DataSet ConvertXMLFileToDataSet(string xmlFile)
            {
                StringReader stream = null;
                XmlTextReader reader = null;
                DataSet xmlDS = null;
                try
                {                lock (this)
                    {
                        XmlDocument xmld = new XmlDocument();
                        xmld.Load(xmlFile);
                        stream = new StringReader(xmld.InnerXml);
                        //从stream装载到XmlTextReader
                        reader = new XmlTextReader(stream);                
                        xmlDS.ReadXml(reader);
                    }
                }
                //catch (System.Exception ex)
                catch
                {
                    //throw ex;
                }
                finally
                {
                    if (reader != null)
                        reader.Close();
                }            return xmlDS;
            }
     /// <summary>
            /// 将DataSet转换为xml文件
            /// </summary>
            /// <param name="xmlDS"></param>
            /// <param name="xmlFile"></param>
            public static void ConvertDataSetToXMLFile(DataSet xmlDS, string xmlFile)
            {
                MemoryStream stream = null;
                XmlTextWriter writer = null;            try
                {
                    stream = new MemoryStream();
                    //从stream装载到XmlTextWriter
                    writer = new XmlTextWriter(stream, Encoding.Unicode);                //用WriteXml方法写入文件.
                    xmlDS.WriteXml(writer);
                    int count = (int)stream.Length;
                    byte[] arr = new byte[count];
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Read(arr, 0, count);                //返回Unicode编码的文本
                    UnicodeEncoding utf = new UnicodeEncoding();
                    StreamWriter sw = new StreamWriter(xmlFile);
                    if (!System.IO.File.Exists(xmlFile))
                    {
                        sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        sw.WriteLine(utf.GetString(arr).Trim());
                    }
                    sw.Close();
                }
                catch (System.Exception ex)
                {
                    //throw ex;
                }
                finally
                {
                    if (writer != null)
                        writer.Close();
                }
            }
      

  3.   

     /// <summary>
            /// 获取节点的值
            /// </summary>
            /// <param name="xmlPath">文件路径+文件名</param>
            /// <param name="strAppKey">键名</param>
            /// <returns></returns>
            public string GetXmlNodeValue(string xmlPath, string strAppKey)
            {
                XmlNode xNode;
                string strResult = "";
                XmlDocument xDoc = new XmlDocument();
                try
                {
                    xDoc.Load(xmlPath);
                    if (xDoc.HasChildNodes)
                    {
                        for (int i = 0; i < xDoc.ChildNodes.Count; i++)
                        {
                            xNode = xDoc.ChildNodes[i];
                            if (xNode.Name == strAppKey)
                            {
                                strResult = xNode.InnerText;
                                break;                        }
                            else
                            {
                                if (xNode.HasChildNodes)
                                {
                                    strResult = GetXmlNodeValue(xNode, strAppKey);
                                    if (strResult != "")
                                    {
                                        break;
                                    }
                                }
                            }
                        }                }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                { }
                return strResult;
            }
      

  4.   

    使用 SelectNodes
     string _Xml = @"<Discover xmlns=""urn:schemas-microsoft-com:xml-analysis""> 
      <RequestType>DISCOVER_XML_METADATA </RequestType> 
      <Restrictions> 
        <RestrictionList> 
          <ObjectExpansion>ObjectProperties </ObjectExpansion> 
        </RestrictionList> 
      </Restrictions> 
      <Properties> 
        <PropertyList> 
        </PropertyList> 
      </Properties> 
    </Discover>";            XmlDocument _Documnet = new XmlDocument();
                _Documnet.LoadXml(_Xml);            XmlNamespaceManager _Manager = new XmlNamespaceManager(_Documnet.NameTable);
                _Manager.AddNamespace("XML", "urn:schemas-microsoft-com:xml-analysis");
                XmlNodeList _List = _Documnet.SelectNodes("//XML:ObjectExpansion", _Manager);
      

  5.   

    使用XPath,这个用起来很方便的.