简体   繁体   中英

how to read and print specific attributes from xml c #

Lets say I have xml file:

<?xml version="1.0" encoding="utf-8"?>
<Test Description="Test XML" VersionFormat="123" ProtectedContentText="(Test test)">
    <Testapp>
        <TestappA>
            <A Id="0" Caption="Test 0" />
            <A Id="1" Caption="Test 1" />
            <A Id="2" Caption="Test 2" />
            <A Id="3" Caption="Test 3">
                <AA>
                    <B Id="4" Caption="Test 4" />
                </AA>
            </A>
        </TestappA>
        <AA>
            <Reason Id="5" Caption="Test 5" />
            <Reason Id="6" Caption="Test 6" />
            <Reason Id="7" Caption="Test 7" />
        </AA>
    </Testapp>
</Test>

I need to read the values of attributes Caption from this xml without using LINQ as the purpose of this code is perform this in Unity3D, after spending all night to make this real I wrote a code which doesn't work. Please help!

code snipped:

// XML settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;                        

// Loop through the XML to get all text from the right attributes
using (XmlReader reader = XmlReader.Create(sourceFilepathTb.Text, settings))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        {
            if (reader.HasAttributes)
            {
                if (reader.GetAttribute("Caption") != null)
                {                                
                    MessageBox.Show(reader.GetAttribute("Caption"));
                }                            
            }
        }
    }
}

Here's how I handle xml: First I load XmlDocument with my xml

XmlDocument x = new XmlDocument();
x.Load("Filename goes here");

Then to grab attributes we have a couple options. If you just want all the captions and don't really care about anything else, you can do this:

XmlNodeList xnl = x.GetElementsByTagName("A");
foreach(XmlNode n in xnl)
   MessageBox.Show(n.Attribute["Caption"].Value);

and repeat that for each Element Tag you have.

I'd need to know more about your requirements before I could offer better advice though.

You can use XPath to get the list

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstring); // Or use doc.Load(filename) to load from file
XmlNodeList attributes = doc.DocumentElement.SelectNodes("//@Caption");
foreach (XmlAttribute attrib in attributes)
{
    Messageox.Show(attrib.Value);
}

We are using the @ notation to select all the nodes in the current document with a Caption attribute. More info on xpath - http://www.w3schools.com/xpath/xpath_syntax.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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