C#xdocument从元素读取并将值放入字符串 [英] C# xdocument read from element and put the value into string

查看:2093
本文介绍了C#xdocument从元素读取并将值放入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。
这是我第一次使用c#中的xml文档

I have a problem. This is the first time i work with a xml document in c#

我有一个像这样的XML文档:

I have a XML document like this:

  <root>
    <GLOBAL>
        <copy>@srcdir@c:\test1\test.txt, @destdir@C:\test1\test.txt</copy>
    </GLOBAL>
  </root>

现在我想在c#中加载xml(使用xdocument完成)的应用程序,一个选项(在这种情况下是全局的),然后它获取复制元素,和copie的这个元素中列出的文件。

Now i want to make an application in c# that loads the xml (done using xdocument), you chose an option (in this case global) and then it gets the copy element, and copie's the files listed in this element.

我有复制功能工作,加载xml

I have the copy function working, loading the xml is done, but getting the srcdir and destdir in an variable is a problem.

任何一个可以帮助我走上正确的轨道?

Any one which can help me getting on the right track?

关心,

推荐答案

使用 Linq Xml ,您可以这样做。

Using Linq to Xml you could do this.

    XDocument doc = XDocument.Load(filepath);       
    var copyitems = doc.Descendants("GLOBAL")   // Read all descendants     
        .Select(s=> 
            {
                var splits = s.Value.Split(new string[] {"@srcdir@", "@destdir@"}, StringSplitOptions.RemoveEmptyEntries); // split the string to separate source and destination.
                return new { Source = splits[0].Replace(",",""), Destination = splits[1].Replace(",","")};
            })
        .ToList();

现在您可以将源和目标读为...

Now you can read source and destination as...

    foreach(var copy in copyitems)
    {
        Console.WriteLine("{0}- {1}", copy.Source, copy.Destination);
    } 

输出

c:\test1\test.txt - C:\test1\test.txt

检查此 演示

这篇关于C#xdocument从元素读取并将值放入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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