Skip to main content
 首页 » 编程设计

c#之使用 C# 在 XML 中获取具有特定名称的标签

2024年02月05日11leader

我有 XML 文件并将其解析为 XDocument。 我需要获取名称为 <Entity> 的所有标签, 但有一个问题。

标记 <Entity>包含另外两个实体标签作为他的 child 。 (还有许多其他标签)。

当我这样做时:

var entity= xmlDoc.Descendants().Where(x => x.Name.LocalName == "Entity"); 

我当然明白了。

有没有办法告诉我:获取所有实体标签,但不是实体标签的子实体标签?

结构如下:

<Entity> --> I need to get this one 
   <SomeTags>Value</SomeTags> 
   <First> 
     <Entity>Value</Entity> --> Skip this one 
   </First> 
   <Entity>Value<Entity> --> Skip this one as well 
</Entity> 

请您参考如下方法:

您可以使用以下内容:

private String path= @"C:\Temp\xml.xml"; //YOur XML path 
public string getValue(string Name) 
{ 
    try 
    { 
        doc = XDocument.Load(path); 
        var dada = (from c in doc.Descendants(Name) 
                    where c.Parent.Name!=Name 
                    select c).First(); 
        return dada.Value; 
    } 
    catch (Exception) 
    { 
        global::System.Windows.Forms.MessageBox.Show("There was a problem with the XML"); 
        return ""; 
    } 
}