部分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>
Run Code Online (Sandbox Code Playgroud)
我想检查每个节点,如果属性split存在,请尝试在变量中分配属性值.
在循环中,我尝试:
foreach (XmlNode xNode in nodeListName)
{
if(xNode.ParentNode.Attributes["split"].Value != "")
{
parentSplit = xNode.ParentNode.Attributes["split"].Value;
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果条件只检查值而不是属性的存在,那我就错了.我应该如何检查属性的存在?
Pau*_*aul 42
您实际上可以直接索引到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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的代码处理XmlElements对象(而不是XmlNodes),则有方法XmlElement.HasAttribute(字符串名称).
因此,如果您只是在元素上查找属性(从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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
仅适用于新手:最新版本的 C# 允许使用?运算符来检查空值分配
parentSplit = xNode.ParentNode.Attributes["split"]?.Value;
Run Code Online (Sandbox Code Playgroud)
您可以使用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())
{
}
}
Run Code Online (Sandbox Code Playgroud)
要么
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
var splitEle = xn.Attributes["split"];
if (splitEle !=null){
return splitEle .Value;
}
Run Code Online (Sandbox Code Playgroud)