c#XML read:读取具有相同节点名称的节点

时间:2017-04-13 09:04:08

标签: c# arrays xml

我的下面的XML包含更多“字符串”节点(字符串节点的数量由工具定义 - 添加了多少种语言) 我使用system.xml将每个节点保存为一个字符串,如下面的代码所示:

是否可以选择将每个“字符串”的InnerText保存到数组中? 我也尝试了下面的代码(for循环),但不知道如何定义循环数(stringnumber)。 任何建议将不胜感激。

valid = TBElement.GetElementsByTagName("Valid")[0].InnerText;

for (int b = 0; b == stringnumber; b++)
{
    languages[b] = TBElement.GetElementsByTagName("Languages/string")[0].InnerText;
}

这是XML:

<ArrayOfGlobalInfo>
 <GlobalInfo>
  <NumberOfEntries>2</NumberOfEntries>
  <LanguageNewDefaultOptions />
  <Languages>
    <string>eng</string>
    <string>ger</string>
    <string>ita</string>
    <string>fre</string>
  </Languages>
  <Valid>true</Valid>
 </GlobalInfo>
</ArrayOfGlobalInfo>

5 个答案:

答案 0 :(得分:0)

循环次数可以从下面找到

TBElement.GetElementsByTagName("Languages/string").Count()

只需将其存储在变量中并在循环条件中使用它

 var stringnumber = TBElement.GetElementsByTagName("Languages/string").Count()

答案 1 :(得分:0)

您可以这样:

XDocument xdoc = XDocument.Load("YourXMLFile");
XmlNodeList elemList = xdoc.GetElementsByTagName("string");
        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine(elemList[i].InnerText);
        }

另一种解决方案就是这样:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Your file path");
XmlNodeList dataNodes = xmlDoc.SelectNodes("/ArrayOfGlobalInfo/GlobalInfo/Languages/string");

foreach (XmlNode node in dataNodes)
                {
//Your code goes here
}

答案 2 :(得分:0)

试试这个:

var stringElements = TBElement.GetElementsByTagName("Languages/string");
List<string> languages = new List<string>();

foreach (var element in stringElements)
    languages.Add(element.InnerText);

如果您更喜欢数组:

var stringElements = TBElement.GetElementsByTagName("Languages/string");
string[] languages = new string[stringElements.Count];

for (int i = 0; i != stringElements.Count; ++i)
    languages[i] = stringElements[i].InnerText;

答案 3 :(得分:0)

在一条指令中使用XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication49
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            string[] languages = doc.Descendants("string").Select(x => (string)x).ToArray();

        }

    }
}

答案 4 :(得分:0)

直接回答你的问题是:

xmlNodeList.Cast<XmlNode>().Select(n => n.InnerText).ToArray();

...其中xmlNodeList是您在GetElementsByTagName()中成功计算的XPath表达式的结果。

但你可能会考虑:

  • 您是否可以更好地使用XDocument而不是XmlDocument
  • 您是否真的需要一个数组,因为XmlNodeList已经具有.Count属性

这说明了一些选择:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace _43387906
{
    class Program
    {
        private static string _xml = "<ArrayOfGlobalInfo>\r\n <GlobalInfo>\r\n  <NumberOfEntries>2</NumberOfEntries>\r\n  <LanguageNewDefaultOptions />\r\n  <Languages>\r\n    <string>eng</string>\r\n    <string>ger</string>\r\n    <string>ita</string>\r\n    <string>fre</string>\r\n  </Languages>\r\n  <Valid>true</Valid>\r\n </GlobalInfo>\r\n</ArrayOfGlobalInfo>";

        static void Main(string[] args)
        {
            try
            {
                var xDocument = XDocument.Parse(_xml);
                UseXDocumentVerbose(xDocument);
                UseXDocumentShorter(xDocument);

                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(_xml);

                UseXmlDocument(xmlDocument);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadLine();
        }

        private static void UseXmlDocument(XmlDocument xmlDocument)
        {
            var languages = xmlDocument.SelectNodes("ArrayOfGlobalInfo/GlobalInfo/Languages/string");

            //You can use languages.Count without converting to an array
            for (int i = 0; i < languages.Count; i++)
            {
                Console.WriteLine(languages[i].InnerText);
            }

            //The trick is to use Cast<T>() and ToArray()
            var languagesArray = languages.Cast<XmlNode>().Select(n => n.InnerText).ToArray();

            for (int i = 0; i < languagesArray.Length; i++)
            {
                Console.WriteLine(languagesArray[i]);
            }
        }

        private static void UseXDocumentShorter(XDocument xDocument)
        {
            if (xDocument.Root.Name != "ArrayOfGlobalInfo")
                throw new Exception("Root isn't ArrayOfGlobalInfo");

            var languages = xDocument.Root
                                     .Elements("GlobalInfo")
                                     .SelectMany(i => i.Elements("Languages"))
                                     .SelectMany(l => l.Elements("string"))
                                     .Select(s => s.Value).Where(s => !string.IsNullOrWhiteSpace(s))
                                     .ToArray();

            for (int i = 0; i < languages.Length; i++)
            {
                Console.WriteLine(languages[i]);
            }
        }

        private static void UseXDocumentVerbose(XDocument xDocument)
        {
            if (xDocument.Root.Name != "ArrayOfGlobalInfo")
                throw new Exception("Root isn't ArrayOfGlobalInfo");

            var globalInfoElements = xDocument.Root.Elements("GlobalInfo");

            var languageElements = globalInfoElements.SelectMany(i => i.Elements("Languages"));

            var languages = languageElements.SelectMany(l => l.Elements("string")).Select(s => s.Value).Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();

            for (int i = 0; i < languages.Length; i++)
            {
                Console.WriteLine(languages[i]);
            }
        }
    }
}