使用c#读取xml文件 [英] Read xml file using c#

查看:118
本文介绍了使用c#读取xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文件如下:



I have an xml file as follows:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<row>
		<enum>SerialPort_NotWork</enum>
		<english>Serial Port is not working restart the Computer</english>
	</row>
	<row>
		<enum>SoftwareRun_DemoMode</enum>
		<english>SOFTWARE WILL RUN IN DEMO MODE ONLY</english>



Xml文件包含大约1000 +附近的许多行。我想编写一个接受的函数'Enum'值并返回相关的'英语'值。



我尝试过的方法:



我试过以下




Xml file contains many rows near about 1000+.I want to write a function which accepts 'Enum' value and returns associated 'English' value.

What I have tried:

I tried following

public static string GetString(String code)
      {
          XmlDocument xml = new XmlDocument();
          xml.Load(@"D:\xmlDoc\Eng_Language.xml");
          string firstName = null;
          XmlNodeList xnList = xml.SelectNodes("/Root/Row[Enum='code']");

          foreach (XmlNode xn in xnList)
          {
              firstName = xn["English"].InnerText;
          }
          return firstName;
      }





但我得到XmlNode计数为零。建议如何搜索英语值基于'枚举'值



but i get XmlNode count zero.plz suggest how to search 'English' value based on 'Enum' value

推荐答案

您需要选择枚举包含代码的节点,然后备份一个级别并向下在英语节点中选择它的值。



XPath 就像这样; < br $>


You need to select the nodes where the enum has the code, and then back up one level and go down in the english node and select it's value.

The XPath for that would look something like this;

/root/row/enum[.=\"code"]/parent::row/english





或代码;





Or in code;

class Program {

    // This returns an IEnumerable<string> in case there are many <row>s with the same <enum>s.
    static IEnumerable<string> GetEnglishString(XPathNavigator navigator, string code) {
        var path = String.Format("/root/row/enum[.=\"{0}\"]/parent::row/english", code);
        return navigator.Select(path).Cast<XPathNavigator>().Select(n => n.Value);
    }

    static void Main(string[] args) {

        var document = new XmlDocument();
        document.Load(@"C:\Temp\XmlExample\Eng_Language.xml");

        var navigator = document.CreateNavigator();

        var notWorking = GetEnglishString(navigator, "SerialPort_NotWork").FirstOrDefault();
        var demoMode = GetEnglishString(navigator, "SoftwareRun_DemoMode").FirstOrDefault();

        Console.WriteLine("notWorking={0}", notWorking);
        Console.WriteLine("demoMode={0}", demoMode);
    }
}





希望这会有所帮助,

Fredrik



Hope this helps,
Fredrik


尝试以下代码。

try following code.
 public static string Get_XML_Text(string enumText)
        {
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                //doc.LoadXml(File.ReadAllText("your xml file Path"));
                doc.LoadXml(@"
	<row>
		<enum>SerialPort_NotWork</enum>
		<english>Serial Port is not working restart the Computer</english>
	</row>
	<row>
		<enum>SoftwareRun_DemoMode</enum>
		<english>SOFTWARE WILL RUN IN DEMO MODE ONLY</english>
</row>
");
                string firstName = null;
                XmlNodeList xnList = doc.SelectNodes("/root/row/enum");
                foreach (XmlNode item in xnList)
                {
                    if (item.InnerText.Trim().Equals(enumText, StringComparison.InvariantCultureIgnoreCase))
                    {
                        firstName = xnList.Item(0).ParentNode.SelectNodes("//english").Item(0).InnerText;
                        break;
                    }
                }
                return firstName;
            }
            catch (Exception)
            {

                throw;
            }
        }



如有任何问题请告诉我。


if any issue then let me know.


Pure Linq to XML声明:

Pure Linq to XML statement:
XmlDocument xdoc = XmlDocument.Load(@"D:\xmlDoc\Eng_Language.xml");
          var nodes = xdoc.Descendants("row")
                          .Where(x=>(string)x.Element("enum").Value == "code")
                          .Select(x=>(string)x.Element("english").Value);



如需了解更多信息,请参阅:

LINQ to XML [ ^ ]

基本查询(L INQ to XML) [ ^ ]

LINQ to XML Overview [ ^ ]

针对XPath用户的XML到XML [ ^ ]


For further information, please see:
LINQ to XML[^]
Basic Queries (LINQ to XML)[^]
LINQ to XML Overview[^]
LINQ to XML for XPath Users[^]


这篇关于使用c#读取xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆