【问题标题】:How to return XML as separate values using XDocument and XElement如何使用 XDocument 和 XElement 将 XML 作为单独的值返回
【发布时间】:2013-01-21 21:45:47
【问题描述】:

我正在尝试使用 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 和日志值感到困惑。任何帮助表示赞赏。

【问题讨论】:

  • 您根本没有展示您要返回的内容。 (也不清楚为什么你不只是询问这些值。)

标签: c# .net xml linq


【解决方案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
 }

您将获得outputPathoutputPath_todaylog 的值到匿名对象的IEnumerable 中。这些对象每个都将具有属性outputPathoutputPath_todaylog,其值由 XML 填充。

【讨论】:

    猜你喜欢
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多