开发者

C# : Getting all nodes of XML doc

开发者 https://www.devze.com 2023-04-05 14:38 出处:网络
Is there a simple way, to get all nodes from an xml document?开发者_JS百科 I need every single node, childnode and so on, to check if they have certain attributes.

Is there a simple way, to get all nodes from an xml document?开发者_JS百科 I need every single node, childnode and so on, to check if they have certain attributes.

Or will I have to crawl through the document, asking for childnodes?


In LINQ to XML it's extremely easy:

XDocument doc = XDocument.Load("test.xml"); // Or whatever
var allElements = doc.Descendants();

So to find all elements with a particular attribute, for example:

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute("foo") != null);

That's assuming you wanted all elements. If you want all nodes (including text nodes etc, but not including attributes as separate nodes) you'd use DescendantNodes() instead.

EDIT: Namespaces in LINQ to XML are nice. You'd use:

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute(XNamespace.Xmlns + "aml") != null);

or for a different namespace:

XNamespace ns = "http://some.namespace.uri";

var matchingElements = doc.Descendants()
                          .Where(x => x.Attribute(ns + "foo") != null);


see here: Iterating through all nodes in XML file

shortly:

 string xml = @"
    <parent>
      <child>
        <nested />
      </child>
      <child>
        <other>
        </other>
      </child>
    </parent>
    ";

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }


In my opinion the simplest solution is using XPath. Also this works if you have .NET 2:

var testDoc = new XmlDocument();
testDoc.LoadXml(str);
var tmp = testDoc.SelectNodes("//*"); // match every element


XDocument.Descendants will return you all the nodes in a flat enumerable.


Check out LINQ to XML. That does what you need.

http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

You can use the SelectMany extension for example.

But if you want to check the values you can just use LINQ to create where-statements.


public void AddWithChildren(XmlNode xnod, Int32 intLevel) //,XmlDocument xmlDoc
    {  
        List<IEnumerable> item = new List<IEnumerable>();
        XmlNode xnodWorking;
        String strIndent = new string('-', 2 * intLevel);
        String strIndent1 = new string('@', 2 * intLevel);
        if (xnod.NodeType == XmlNodeType.Element)
        {
            item.Add(new ListXML(strIndent + xnod.Name, strIndent + xnod.Name, ""));
            XmlNamedNodeMap mapAttributes = xnod.Attributes;
            foreach (XmlNode xnodAttribute in mapAttributes)
            {
                item.Add(new ListXML(strIndent1 + xnodAttribute.Name, strIndent1 + xnodAttribute.Name, ""));
            }
            if (xnod.HasChildNodes)
            {
                xnodWorking = xnod.FirstChild;
                while (xnodWorking != null)
                {
                    AddWithChildren(xnodWorking, intLevel + 1);
                    xnodWorking = xnodWorking.NextSibling;
                }
            }
        }
    }


  protected void Page_Load(object sender, EventArgs e)
  {

            XmlDocument document = new XmlDocument();

            string xmlStr;
            using (var wc = new WebClient())
            {
                xmlStr = wc.DownloadString("test.xml");
            }

            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xmlStr);

            XmlNode xnod = xmlDoc.DocumentElement;

           AddWithChildren(xnod, 1);
 }


string AttrNameerr = "err";//find error code in xml
XmlReader rdr = XmlReader.Create(new stem.IO.StringReader(somesXMLtring));//somesXMLtring is xml in string variable we want to find attribute in.
while (rdr.Read())
{
    if (rdr.NodeType == XmlNodeType.Element)
    {
      //Found the new element, now check if the required attribute is present or not. if not, ignore, if yes then display the same
      string val = rdr.GetAttribute(AttrNameerr);//AttrNameerr is name of attribute we need to get value of which. here we are searching for error code stored as value of 'err' attribute

        if (val != null)
          textBox.Text = strResult = "error = " + rdr.GetAttribute(AttrNameerr);

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消