Read the values from XML file

2019-07-19 01:47发布

问题:

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