【发布时间】:2017-11-18 14:06:39
【问题描述】:
我有一些 XML 文件可以在结构 <funding-source><institution-wrap>...</institution-wrap></funding-source> 中有一些节点
我想获取节点内的值(如果有)并将这些值与另一个 XML 文件即 funding_info.xml 的节点 <skos> 匹配,如果有匹配项,则取属性值它的父节点<skd> 然后
将主 XML 文件的 <funding-source><institution-wrap>...</institution-wrap></funding-source> 替换为 <funding-source><institution-wrap>...</institution-wrap><fundref-id>The attribute value found</fundref-id></funding-source>。
funding_info.xml 如下所示
<?xml version="1.0" encoding="UTF-8"?>
<item>
<skd id="inst/10.1.3169">
<skosl>
<skos>NSF</skos>
</skosl>
<skosl>
<skos>National Science Foundation</skos>
</skosl>
<skosl>
<skos>Jatio Bigyan Songothon</skos>
</skosl>
</skd>
<skd id="inst/10.1.4560">
<skosl>
<skos>Massachusetts Institute of Technology</skos>
</skosl>
<skosl>
<skos>MIT</skos>
</skosl>
<skosl>
<skos>Massachusetts Institute of Technology, USA</skos>
</skosl>
</skd>
<skd id="inst/11.2.30213">
<skosl>
<skos>European Union</skos>
</skosl>
<skosl>
<skos>European Union</skos>
</skosl>
<skosl>
<skos>European Union FP7 Programme</skos>
</skosl>
</skd>
</item>
例如,如果我要修改的 XML 文件包含一些节点,例如
<funding-source><institution-wrap>NSF</institution-wrap></funding-source>
<funding-source><institution-wrap>Caltech</institution-wrap></funding-source>
<funding-source><institution-wrap>Massachusetts Institute of Technology, USA</institution-wrap></funding-source>
输出应该是
<funding-source><institution-wrap>NSF</institution-wrap><fundref-id>10.1.3169</fundref-id></funding-source>
<funding-source><institution-wrap>Caltech</institution-wrap></funding-source>
<funding-source><institution-wrap>Massachusetts Institute of Technology, USA</institution-wrap><fundref-id>10.1.4560</fundref-id></funding-source>
由于在 funding_info.xml 的任何 <skos> 节点中都没有找到 Caltech,因此它的值没有改变。
我不知道如何解决这个问题,但下面是我尝试过但中途卡住的方法
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@"C:\Users\Desktop\my_sample.xml", LoadOptions.PreserveWhitespace);
var x = doc.Descendants("funding-source").Elements("institution-wrap").Select(a => a.Value).ToArray();
if (x.Any())
{
foreach (var cont in x)
{
XDocument doc2 = XDocument.Load(@"C:\Users\Desktop\funding_info.xml",
LoadOptions.PreserveWhitespace);
var y = doc2.Descendants("skos").Ancestors("skosl").Ancestors("skd").Attributes("id")
.Select(a => a.Value);
if (doc2.Descendants("skos").Any().Value(cont))
{
var y = doc2.Descendants("skos").Ancestors("skosl").Ancestors("skd").Attributes("id")
.Select(a => a.Value).First();
............. ...................
............. ..................
}
}
}
Console.ReadLine();
}
【问题讨论】:
标签: c# linq-to-xml