在C#中检索Xml属性值

时间:2017-03-19 11:53:41

标签: c# asp.net xml

我是C#&我正在尝试从我的Asp.net web项目中的XML文件中读取XML属性,当我检索属性内容时,我得到以下结果: “System.XML.Attribute;”

这是XML文件:

<?xml version="1.0" encoding="UTF-8" standalone="true"?>

<!--creating XML file-->

<Document PagesInDocument="1" Filename="YahyaXML">
    <Page Filename="YahyaXML" ZonesInPage="1" PageID="0">
        <Zone TextLinesInZone="2" zoneLRY="558" zoneLRX="1202" 
            zoneULY="3" zoneULX="886" ZoneID="0">

            <TextLine Content="aaaaaaaaaaa" TextLineID="0"/>

            <TextLine Content="aaaaaaaaaaaaaaaaaa" TextLineID="1"/>
        </Zone>
    </Page>
</Document>

这是我的c#代码:

        XmlDocument doc = new XmlDocument();
        doc.Load(@"C:\Program Files (x86)\NovoDynamics\NovoVerus\api\examples\C#Samples\WebAppTest\Uploads\test-ht.xml");
        StringBuilder Content_Value = new StringBuilder();


        XmlNodeList aNodes = doc.SelectNodes("/Document/Page/Zone");

        XmlNodeList bNodes = doc.SelectNodes("/Document/Page/Zone/TextLine");

        foreach (XmlNode aNode in aNodes)
        {
            XmlAttribute ULX_xml = aNode.Attributes["zoneULX"];
            XmlAttribute ULY_xml = aNode.Attributes["zoneULY"];
            XmlAttribute LRX_xml = aNode.Attributes["zoneLRX"];
            XmlAttribute LRY_xml = aNode.Attributes["zoneLRY"];

            if (ULX_xml.Value == TextBox5.Text &&  ULY_xml.Value == TextBox6.Text && LRX_xml.Value == TextBox7.Text && LRY_xml.Value == TextBox8.Text )
            {


            foreach (XmlNode bNode in bNodes)
            {
                //XmlAttribute ContentAttribute = bNode.Attributes["Content"];

                if (bNode.Attributes["Content"].Value != null)
                {
                    Content_Value.Append(bNode.Attributes["Content"].Value.ToString());


                }


            }

            Content_Value.Append("\n");

            }

        }


        TextBox9.Text = Content_Value.ToString();

2 个答案:

答案 0 :(得分:0)

您的代码有效。尝试将xml文件中的第一个字符串更改为:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

更多:https://msdn.microsoft.com/en-us/library/ms256048(v=vs.120).aspx

答案 1 :(得分:0)

使用xml Linq

<ul>
    {% for team in atlanticsoccer %}
        <li>{{team.location}}</li>
        <li>{{team.team_name}}</li>
        <li>{{team.league.name}}</li>
        <li>{{team.league.sport}}</li>
    {% endfor %}
</ul>