0

我正在尝试使用 XDocument 和 XElement 从 XML 文档中获取值。我正在尝试获取三个值,但是当我尝试返回它们时,它们会合并为一个值。这是我正在搜索的 XML:

<create_maint_traveler>     
<Paths>
        <outputPath value="D:\Intercim\DNC_Share\itcm\DataInput\MCDHeaderDrop\" />
        <outputPath_today value="D:\Intercim\DNC_Share\itcm\DataInput\Today\" />
        <log value="D:\Intercim\DNC_Share\itcm\Log\CreateMaintLog.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:\Intercim\DNC_Share\itcm\DataInput\MCDHeaderDrop\D:\Intercim\DNC_Share\itcm\DataInput\Today\D:\Intercim\DNC_Share\itcm\Log\CreateMaintLog.log

否则将一无所有。我在标签之外有 XML 文件中的值,之前返回了一个 long 值。我对如何分别返回 outputPath、outputPath_today 和日志值感到困惑。任何帮助表示赞赏。

4

1 回答 1

1

尝试:

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_todaylog匿名IEnumerable对象的值。这些对象每个都将具有属性outputPathoutputPath_today并且log具有从 XML 填充的值。

于 2013-01-21T21:54:21.640 回答