如何在C#中读取示例节点内的文本?

时间:2011-07-21 12:15:40

标签: c# xml parsing xml-parsing

这是我想要阅读的XML。

<Server ServerName="SP-SWD-T01">
    Some nodes are there 
</Server>

我想阅读服务器内部的ServerName,我该如何阅读它。请帮助。

这是代码

XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.IgnoreComments = false;
            XmlReader xmlRdr = XmlReader.Create(strFilePath, readerSettings);
            // Parse the file
            while (xmlRdr.Read())
            {
                switch (xmlRdr.NodeType)
                {
                    case XmlNodeType.Element:
                        // You may need to capture the last element to provide a context
                        // for any comments you come across... so copy xmlRdr.Name, etc.
                        break;
                    case XmlNodeType.Comment:
                        MessageBox.Show(xmlRdr.Name);
                        break;

                    case XmlNodeType.Text: //Display the text in each element.
                        //Console.WriteLine(reader.Value);
                        break;
                    case XmlNodeType.EndElement: //Display the end of the element.
                        //Console.Write("</" + reader.Name);
                        //Console.WriteLine(">");
                        break;
                }
            }

由于

1 个答案:

答案 0 :(得分:1)

试试这个

String xml = @"<Server ServerName=""SP-SWD-T01"">Some nodes are there</Server>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
String servername = doc.SelectSingleNode("/Server").Attributes["ServerName"].Value;