问题
I have a problem. This is the first time i work with a xml document in c#
I have a XML document like this:
<root>
<GLOBAL>
<copy>@srcdir@c:\test1\test.txt, @destdir@C:\test1\test.txt</copy>
</GLOBAL>
</root>
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.
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?
Kind regards,
回答1:
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);
}
Output:
c:\test1\test.txt - C:\test1\test.txt
Check this Demo
回答2:
Maybe You should try to do something like this :
<copy src="c:\test1\test.txt" dest="C:\test1\test.txt"/>
And get attribut instead.
来源:https://stackoverflow.com/questions/36865982/c-sharp-xdocument-read-from-element-and-put-the-value-into-string