【问题标题】:Read the values from XML file从 XML 文件中读取值
【发布时间】:2018-06-10 12:13:07
【问题描述】:

我正在使用 XDocument 来加载 XML 文件,使用此内容,我正在尝试读取 <pjob:job_variables> 节点内容,并为 <pjob:job_variables> 中的每个节点获取名称和值, 所以<pjob:var name="XMLFilePath">E:\PP\REPC.xt</pjob:var> 得到名称XMLFilePath 和它的值E:\PP\REPC.xt

<?xml version="1.0"?>
<?P_command version="1.0"?>
<pjob:job_command xmlns:pjob="http://www.pp.com/schemas" name="SubmitJob">
    <pjob:job_variables>
        <pjob:var name="XMLFilePath">E:\PP\REPC.xt</pjob:var>
        <pjob:var name="TSLFilePath">E:\PP\REPC.tl</pjob:var>
        <pjob:var name="_sys_BitmapType">jpeg</pjob:var>
        .........
    </pjob:job_variables>
    <pjob:doc_variables>  
        <pjob:var name="CompanyPhone"/>
        <pjob:var name="CompanyWebsite">www.site.com</pjob:var>    
        .........
    </pjob:doc_variables>
</pjob:job_command>

我尝试了很多变化,比如

string name, value = String.Empty;
XDocument doc = XDocument.Load("../assets/packet.xml");
var authors = doc.Descendants("job_variables");
foreach (var node in nodes)
{
  name = node.name;
  value = node.value;
}

但他没有找到Descendants,我怎么才能找到它?

【问题讨论】:

  • 当你的xml有命名空间you need to use them
  • 尝试使用 DescendantNodes 而不是 Descendants

标签: c# xml linq-to-xml


【解决方案1】:

您只需添加命名空间pjob

XNamespace ns = "http://www.pp.com/schemas";
XDocument doc = XDocument.Load("../assets/packet.xml");
var authors = doc.Root.Element(ns + "job_variables").Elements();

或者使用XName.Get()方法:

var authors = doc.Root.Element(XName.Get("job_variables", "http://www.pp.com/schemas")).Elements();

这将获取“job_variables”元素的所有子元素。

按照 cmets 中的规定,要同时获取 job_variablesdoc_variables 的元素,您甚至不需要通过它们的名称来访问这些元素;只需使用doc.Root.Elements().Elements()

【讨论】:

    【解决方案2】:

    尝试以下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
    
                XElement job_command = doc.Descendants().Where(x => x.Name.LocalName == "job_command").FirstOrDefault();
                XNamespace pjobNs = job_command.GetNamespaceOfPrefix("pjob");
    
                var results = job_command.Descendants(pjobNs +  "var").Select(x => new {
                    name = (string)x.Attribute("name"),
                    value = (string)x
                }).ToList();
            }
        }
    }
    

    【讨论】:

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