【发布时间】:2018-08-31 14:53:31
【问题描述】:
我正在尝试创建一个具有以下步骤的程序:
1) 从用户给定路径获取所有xml文件
2)打开每个文件(如果有)并搜索节点<institution>,格式为<funding-source><institution-wrap><institution>...</institution></institution-wrap></funding-source>
3) 获取节点<institution>的值,并在节点<skosxl:literalForm xml:lang="...">内的database xml中搜索准确值
4)如果找到,则得到其父节点<skos:Concept rdf:about="...">减去字符串http://dx.doi.org/
5) 在xml文件中<institution>节点之后添加一个节点<institution-id institution-id-type="fundref">,其值类似于<funding-source><institution-wrap><institution>...</institution><institution-id institution-id-type="fundref">VALUE of the rdf:about attribute</institution-id></institution-wrap></funding-source>
这是一个示例 input file 和该文件的 desired output。
我尝试过的:
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();
但它不起作用...有人可以帮忙...
【问题讨论】:
标签: c# xml-parsing linq-to-xml