Read the values from XML file

懵懂的女人 提交于 2019-12-24 02:47:20

问题


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;
}

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


回答1:


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();

Or use the XName.Get() method:

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

This gets all children of the "job_variables" element.

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().




回答2:


try following :

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();
        }
    }
}


来源:https://stackoverflow.com/questions/50783559/read-the-values-from-xml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!