我正在尝试使用XDocument和XElement从XML文档中获取值。我正在尝试获取三个值,但是当我尝试返回它们时,它们会合并为一个值。这是我正在搜索的 XML:
<create_maint_traveler>
<Paths>
<outputPath value="D:IntercimDNC_ShareitcmDataInputMCDHeaderDrop" />
<outputPath_today value="D:IntercimDNC_ShareitcmDataInputToday" />
<log value="D:IntercimDNC_ShareitcmLogCreateMaintLog.log" />
</Paths>
</create_maint_traveler>
以下是我查询值的方式:
XDocument config = XDocument.Load(XML);
foreach (XElement node in config.Root.Elements("Paths"))
{
if (node.Name == "outputPath") outputPath = node.Value;
if (node.Name == "outputPath_today") outputPath = node.Value;
if (node.Name == "log") outputPath = node.Value;
}
当我输出到文件时,我发现返回的值是
D:IntercimDNC_ShareitcmDataInputMCDHeaderDropD:IntercimDNC_ShareitcmDataInputTodayD:IntercimDNC_ShareitcmLogCreateMaintLog.log
否则什么都不会返回。我在标记之外的XML文件中具有值,该标记返回了一个长值。我对如何分别返回输出路径、outputPath_today和日志值感到困惑。任何帮助,不胜感激。
尝试:
var xDoc = XDocument.Load(XML);
var paths = xDoc.Root.Elements("Paths");
var res = from p in paths
select new
{
outputPath = p.Element("outputPath").Attribute("value").Value,
outputPath_today = p.Element("outputPath_today").Attribute("value").Value,
log = p.Element("log").Attribute("value").Value
};
foreach(path in res)
{
System.Console.WriteLine(path.outputPath);
System.Console.WriteLine(path.outputPath_today);
System.Console.WriteLine(path.log);
// or do anything you want to do with those properties
}
您将获得outputPath
、outputPath_today
和log
的值,并IEnumerable
匿名对象。这些对象每个对象都有属性outputPath
、outputPath_today
和log
,其值是从XML填充的。