从XML文件读取值 [英] Read the values from XML file

查看:102
本文介绍了从XML文件读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XDocument来加载具有此内容的XML文件,我正在尝试读取<pjob:job_variables>节点的内容,并为<pjob:job_variables>中的每个节点获取名称和值, 因此对于<pjob:var name="XMLFilePath">E:\PP\REPC.xt</pjob:var>来说,获取名称XMLFilePath及其值E:\PP\REPC.xt

I am using XDocument in order to load XML file, with this content, i am trying to read <pjob:job_variables> nodes content, and for each node in <pjob:job_variables> to get the name and the value, so for <pjob:var name="XMLFilePath">E:\PP\REPC.xt</pjob:var> to get the name XMLFilePath and the value of it 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>

我尝试了很多变化,例如

i tried a lot of variations, like

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,我该如何实现?

but he doesn't find the Descendants, how can i acheive it?

推荐答案

您只需要在名称空间pjob之前添加

You simply need to prepend the namespace 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"元素的所有子项.

This gets all children of the "job_variables" element.

如注释中所指定,要获取job_variablesdoc_variables的元素,您甚至不需要通过它们的名称访问这些元素.只需使用doc.Root.Elements().Elements().

As specified in the comments, to get the elements of both job_variables and doc_variables, you don't even need to access the elements via their names; just use doc.Root.Elements().Elements().

这篇关于从XML文件读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆