使用c#检查XML中是否存在元素

时间:2014-11-16 01:07:39

标签: c# xml

为什么我在hasIdentifier变量中获取false值,当我在第i个文档中看到anything_start_i.xml中有<identifier>value</identifier>元素。

XDocument doc = XDocument.Load(args[0] + "/?verb=GetRecord&metadataPrefix=p3dm&identifier=" + i);
doc.Save("anything_start" + i + ".xml");
bool hasIdentifier = doc.Elements("identifier").Any();
Console.WriteLine(hasIdentifier);

尝试用后代代替元素,再次虚假。

XML:

<?xml version="1.0" encoding="utf-8"?>
    <OAI-PMH xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
      <responseDate>...</responseDate>
      <request verb="GetRecord" identifier="1"</request>
      <GetRecord>
        <record>
          <header>
            <identifier>1</identifier>
            <datestamp>...</datestamp>
          </header>
          <metadata>
            <P3DM xmlns="..." xsi:schemaLocation="...">
              <MODELINFOID>1</MODELINFOID>
              <TITLE>Roth</TITLE>
  ....

好吧,我想保存所有文档,并在没有文档时尝试停止保存(实际上有没有有意义的数据)。所以,这就是我的开始:

static void Main(string[] args)
{
  var i = 1;
  bool work = true;
  do{
    XDocument doc = XDocument.Load(args[0] + "/?verb=GetRecord&metadataPrefix=p3dm&identifier=" + i);
    bool hasIdentifier = doc.Elements("identifier").Any();
    if (hasIdentifier) {
        doc.Save("anything" + i + ".xml");
        i++;
     }else{ 
        work = false;
     }
  } while (work);

1 个答案:

答案 0 :(得分:2)

XNamespace ns = "you namespace goes here";
bool hasIdentifier = doc.Descendants(ns + "identifier").Any();