Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在某个父节点内添加新节点(从另一个xml文件获取值)?_C#_Xml Parsing_Linq To Xml - Fatal编程技术网

C# 在某个父节点内添加新节点(从另一个xml文件获取值)?

C# 在某个父节点内添加新节点(从另一个xml文件获取值)?,c#,xml-parsing,linq-to-xml,C#,Xml Parsing,Linq To Xml,我正在尝试创建一个具有以下步骤的程序: 1从用户给定的路径获取所有xml文件 2打开每个文件(如果有),并搜索其格式为的节点 3获取节点的值,并在节点内部搜索精确值 4如果找到,则获取其父节点的属性值减去字符串 5在xml文件中的节点后面添加一个节点,该节点的值类似于rdf:about属性的…值 下面是该文件的示例和示例 我所尝试的: string pathToUpdatedFile = @"D:\test\Jobs"; var files=Directory.GetFiles(pathToUp

我正在尝试创建一个具有以下步骤的程序:

1从用户给定的路径获取所有xml文件

2打开每个文件(如果有),并搜索其格式为的节点

3获取节点的值,并在节点内部搜索精确值

4如果找到,则获取其父节点的属性值减去字符串

5在xml文件中的节点后面添加一个节点,该节点的值类似于rdf:about属性的…值

下面是该文件的示例和示例

我所尝试的:

string pathToUpdatedFile = @"D:\test\Jobs";
var files=Directory.GetFiles(pathToUpdatedFile,"*.xml");
foreach (var file in files)
{
    var fundingDoc = XDocument.Load(@"D:\test\database.xml");
    XNamespace rdf=XNamespace.Get("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
    XNamespace skosxl = XNamespace.Get("http://www.w3.org/2008/05/skos-xl#");
    XNamespace skos=XNamespace.Get("http://www.w3.org/2004/02/skos/core#");

    var targetAtt = fundingDoc.Descendants(skos+"Concept").Elements(skosxl+"prefLabel")
        .ToLookup(s => (string)s.Element(skosxl+"literalForm"), s => (string)s.Parent.Attribute(rdf+"about"));
    XDocument outDoc = XDocument.Parse(File.ReadAllText(file),LoadOptions.PreserveWhitespace);
    foreach (var f in outDoc.Descendants("funding-source").Elements("institution-wrap"))
    {
        if (f.Element("institution-id") == null)
        {
            var name = (string)f.Element("institution");
            var x = targetAtt[name].FirstOrDefault(); // just take the first one
            if (x != null)

                f.Add(new XElement("institution-id", new XAttribute("institution-id-type","fundref"),x.Substring(@"http://dx.doi.org/".Length)));
        }
        outDoc.Save(file);
    }

    Console.ReadLine();
但它不起作用…有人能帮忙吗…

请参见下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.OleDb;

namespace ConsoleApplication31
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string DATABASE = @"c:\temp\test1.xml";

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement article = doc.Root;
            XNamespace ns = article.GetDefaultNamespace();

            XDocument docDatabase = XDocument.Load(DATABASE);
            XElement rdf = docDatabase.Root;
            XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
            XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");

            List<XElement> prefLabels = rdf.Descendants(nsSkosxl + "prefLabel").ToList();
            Dictionary<string, List<string>> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Element(nsSkosxl + "Label").Attribute(nsRdf + "about"))
                .ToDictionary(x => x.Key, y => y.ToList());

            List<XElement> fundingSources = article.Descendants(ns + "funding-source").ToList();

            foreach (XElement fundingSource in fundingSources)
            {
                XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
                string institution = (string)fundingSource;

                if (dictLabels.ContainsKey(institution))
                {
                    institutionWrap.Add(new XElement("institution-id", new object[] { 
                       new XAttribute("institution-id-type","fundref"),
                       dictLabels[institution]
                    }));
                }
                else
                {
                    Console.WriteLine("Dictionary doesn't contain : '{0}'", institution);
                }

            }
            Console.ReadLine();
        }

    }
}

我想这就是你想要的修改过的jdweng的代码

const string FILENAME = @"c:\temp\test.xml";
const string DATABASE = @"c:\temp\test1.xml";
public static void Main(string[] args)
{
    XDocument doc = XDocument.Load(FILENAME);

    XElement article = doc.Root;
    XNamespace ns = article.GetDefaultNamespace();

    XDocument docDatabase = XDocument.Load(DATABASE);
    XElement rdf = docDatabase.Root;
    XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
    XNamespace nsSkos = rdf.GetNamespaceOfPrefix("skos");
    XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");

    List<XElement> prefLabels = rdf.Descendants(nsSkos + "Concept").ToList();
    Dictionary<string, List<string>> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Parent.Element(nsSkos+"Concept").Attribute(nsRdf + "about").Value.Substring(18))
        .ToDictionary(x => x.Key, y => y.ToList());

    List<XElement> fundingSources = article.Descendants(ns + "funding-source").ToList();

    foreach (XElement fundingSource in fundingSources)
    {
        XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
        string institution = (string)fundingSource;

        if (dictLabels.ContainsKey(institution))
        {
            institutionWrap.Add(new XElement("institution-id", new object[] {
                                                new XAttribute("institution-id-type","fundref"),
                                                dictLabels[institution]
                                             }));
        }
    }
    doc.Save(FILENAME);
    Console.WriteLine("Done");
    Console.ReadLine();
}

但是fundref.xml文件中有多个名称空间,GetDefaultNamespace如何知道哪个节点需要哪个名称空间..另外test.xml是需要修改的文件,数据取自另一个xml文件fundref.xml没有前缀,因此它使用默认名称空间。这就是我获取根节点并提取默认名称空间的原因。我要检查节点机构的内容,然后在database.xml文件中搜索该值,然后获取该值的attrib值,然后将其放入我要修改的xml文件中…其格式中的位置值。。。不会永远是福特基金会如果我无法获得我使用的名称空间,我通常会做以下事情:XElement literalForm=doc.subjections.Wherex=>x.Name.LocalName==literalForm.FirstOrDefault;然后使用:List fundingSources=article.genderantsns+funding-source.ToList;然后在fundingSources{…}中使用ForEachElement fundingSource