简体   繁体   English

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

[英]Check if element exists in XML using c#

Why do I get false value for hasIdentifier variable, when I see in i-th document anything_start_i.xml that there is <identifier>value</identifier> element. 当我在第i个文档Anything_start_i.xml中看到有<identifier>value</identifier>元素时,为什么为hasIdentifier变量得到错误的值。

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

Tried with Descendants instead of Elements, and again false. 尝试使用后代而不是元素,然后再次错误。

XML: 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>
  ....

Well, I would like to save all documents, and trying to stop saving when there is no documents any more (actually there is but without meaningful data). 好吧,我想保存所有文档,并尝试在不再有文档(实际上是文档但没有有意义的数据)时停止保存。 So, this is how i started: 所以,这就是我开始的方式:

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);
XNamespace ns = "you namespace goes here";
bool hasIdentifier = doc.Descendants(ns + "identifier").Any();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM