C# 如何从xml文件中读取值
我有以下XML文件C# 如何从xml文件中读取值,c#,xml,serialization,C#,Xml,Serialization,我有以下XML文件 <?xml version="1.0"?> <MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Items> <Settings xsi:type="FileModel"> <Name>FileRepository</
<?xml version="1.0"?>
<MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<Settings xsi:type="FileModel">
<Name>FileRepository</Name>
<IsActive>true</IsActive>
<IsHidden>false</IsHidden>
</Settings>
<Settings xsi:type="ServerModel">
<Name>DelRep</Name>
<IsActive>false</IsActive>
<IsHidden>false</IsHidden>
</Settings>
</Items>
<DirectoryPath>D:\MainFolder</DirectoryPath>
</MainClass>
此XML文件以字符串形式存储在上面,即字符串wholeContent=File.ReadAllTextthis.FilePath
其中,此文件路径具有指向文件位置的有效路径
wholeContent存储了我稍后使用的整个XML,但现在我有必要将路径存储为字符串。是否有一种方法可以使用wholeContent或什么是合适的方法来实现这一点?我建议不要将XML文档作为字符串加载,而是使用.NET提供的类型,例如XDocument 通过这种方式,访问元素及其值变得非常容易:
XDocument document = XDocument.Load(this.FilePath);
var element = document.Root.Elements().Single(x => x.Name == "DirectoryPath");
var directoryPath = element.Value;