简体   繁体   English

如何检查 XML 中是否存在特定属性?

[英]How do I check particular attributes exist or not in XML?

Part of the XML content:部分 XML 内容:

<section name="Header">
  <placeholder name="HeaderPane"></placeholder>
</section>

<section name="Middle" split="20">
  <placeholder name="ContentLeft" ></placeholder>
  <placeholder name="ContentMiddle"></placeholder>
  <placeholder name="ContentRight"></placeholder>
</section>

<section name="Bottom">
  <placeholder name="BottomPane"></placeholder>
</section>

I want to check in each node and if attribute split exist, try to assign an attribute value in a variable.我想检查每个节点,如果存在属性split ,请尝试在变量中分配一个属性值。

Inside a loop, I try:在循环内,我尝试:

foreach (XmlNode xNode in nodeListName)
{
    if(xNode.ParentNode.Attributes["split"].Value != "")
    {
        parentSplit = xNode.ParentNode.Attributes["split"].Value;
    }
}

But I'm wrong if the condition checks only the value, not the existence of attributes.但是如果条件只检查值而不检查属性的存在,我就错了。 How should I check for the existence of attributes?我应该如何检查属性的存在?

You can actually index directly into the Attributes collection (if you are using C# not VB):您实际上可以直接索引到 Attributes 集合(如果您使用的是 C# 而不是 VB):

foreach (XmlNode xNode in nodeListName)
{
  XmlNode parent = xNode.ParentNode;
  if (parent.Attributes != null
     && parent.Attributes["split"] != null)
  {
     parentSplit = parent.Attributes["split"].Value;
  }
}

If your code is dealing with XmlElements objects (rather than XmlNodes ) then there is the method XmlElement.HasAttribute(string name) .如果您的代码处理XmlElements对象(而不是XmlNodes ),则有方法XmlElement.HasAttribute(string name)

So if you are only looking for attributes on elements (which it looks like from the OP) then it may be more robust to cast as an element, check for null, and then use the HasAttribute method.因此,如果您只是在寻找元素上的属性(从 OP 中可以看出),那么将其转换为元素、检查是否为 null,然后使用 HasAttribute 方法可能会更健壮。

foreach (XmlNode xNode in nodeListName)
{
  XmlElement xParentEle = xNode.ParentNode as XmlElement;
  if((xParentEle != null) && xParentEle.HasAttribute("split"))
  {
     parentSplit = xParentEle.Attributes["split"].Value;
  }
}

Just for the newcomers: the recent versions of C# allows the use of ?仅针对新手:最新版本的 C# 允许使用? operator to check nulls assignments运算符检查空值分配

parentSplit = xNode.ParentNode.Attributes["split"]?.Value;

You can use LINQ to XML,您可以使用 LINQ to XML,

XDocument doc = XDocument.Load(file);

var result = (from ele in doc.Descendants("section")
              select ele).ToList();

foreach (var t in result)
{
    if (t.Attributes("split").Count() != 0)
    {
        // Exist
    }

    // Suggestion from @UrbanEsc
    if(t.Attributes("split").Any())
    {

    }
}

OR要么

 XDocument doc = XDocument.Load(file);

 var result = (from ele in doc.Descendants("section").Attributes("split")
               select ele).ToList();

 foreach (var t in result)
 {
     // Response.Write("<br/>" +  t.Value);
 }
var splitEle = xn.Attributes["split"];

if (splitEle !=null){
    return splitEle .Value;
}

EDIT编辑

Disregard - you can't use ItemOf (that's what I get for typing before I test).无视 - 您不能使用 ItemOf (这是我在测试之前输入的内容)。 I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.如果我能弄清楚如何,我会删除文本……或者我可能会简单地删除答案,因为它最终是错误且无用的。

END EDIT结束编辑

You can use the ItemOf(string) property in the XmlAttributesCollection to see if the attribute exists.您可以使用 XmlAttributesCollection 中的ItemOf(string)属性来查看该属性是否存在。 It returns null if it's not found.如果未找到,则返回 null。

foreach (XmlNode xNode in nodeListName)
{
    if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
    {
         parentSplit = xNode.ParentNode.Attributes["split"].Value;
    }
}

XmlAttributeCollection.ItemOf Property (String) XmlAttributeCollection.ItemOf 属性(字符串)

Another way to handle the situation is exception handling.处理这种情况的另一种方法是异常处理。

Every time a non-existent value is called, your code will recover from the exception and just continue with the loop.每次调用不存在的值时,您的代码都会从异常中恢复并继续循环。 In the catch-block you can handle the error the same way you write it down in your else-statement when the expression (... != null) returns false.在 catch 块中,当表达式 (... != null) 返回 false 时,您可以像在 else 语句中写下错误一样处理错误。 Of course throwing and handling exceptions is a relatively costly operation which might not be ideal depending on the performance requirements.当然,抛出和处理异常是一个成本相对较高的操作,根据性能要求可能并不理想。

You can use the GetNamedItem method to check and see if the attribute is available.您可以使用 GetNamedItem 方法检查属性是否可用。 If null is returned, then it isn't available.如果返回 null,则它不可用。 Here is your code with that check in place:这是您进行该检查的代码:

foreach (XmlNode xNode in nodeListName)
{
    if(xNode.ParentNode.Attributes.GetNamedItem("split") != null )
    {
        if(xNode.ParentNode.Attributes["split"].Value != "")
        {
            parentSplit = xNode.ParentNode.Attributes["split"].Value;
        }
    }  
}

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

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