如何将以下代码转换为C#? 我有一个XML字符串,我需要在其中查找属性名称,同时检查是否存在带有"别名"的父节点。
$atts = $xml.GetElementsByTagName('attribute');
foreach($att in $atts)
{
if($att.ParentNode.HasAttribute('alias'))
{
$attName = $att.ParentNode.GetAttribute('alias') + "." + $att.name
Write-Output $att.ParentNode.GetAttribute('alias') + "." + $att.name
}
else
{
$attName = $att.name
Write-Output $att.name
}
}
答案 0 :(得分:-1)
namespace StackOverflow
{
using System;
using System.Xml;
class XmlTest
{
public static void yourTest()
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("yourXmlPath.xml");
// It is recommended that you use the XmlNode.SelectNodes or XmlNode.SelectSingleNode method instead of the GetElementsByTagName method.
XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("attribute");
foreach(XmlNode xmlNode in xmlNodes)
{
if (xmlNode.ParentNode.Attributes.GetNamedItem("alias") != null)
{
string attributeName = xmlNode.ParentNode.Attributes.GetNamedItem("alias").InnerText + "." + xmlNode.GetNamedItem("name").InnerText;
Console.WriteLine(attributeName);
}
else
{
string attributeName = xmlNode.Attributes.GetNamedItem("name").InnerText;
Console.WriteLine(attributeName);
}
}
}
}
}