C# xdocument 从元素读取并将值放入字符串

C# xdocument read from element and put the value into string

我有问题。 这是我第一次在 c#

中使用 xml 文档

我有一个这样的 XML 文档:

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

现在我想在 c# 中创建一个加载 xml 的应用程序(使用 xdocument 完成),您选择一个选项(在本例中为全局),然后它获取复制元素,然后复制文件在此元素中列出。

我有复制功能,加载 xml 已经完成,但是在变量中获取 srcdir 和 destdir 是个问题。

谁能帮助我走上正轨?

亲切的问候,

也许你应该尝试做这样的事情:

<copy src="c:\test1\test.txt" dest="C:\test1\test.txt"/>

改为获取属性。

使用 LinqXml 你可以做到这一点。

    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();

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

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

输出:

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

勾选这个Demo