开发者

Problem in reading XML

开发者 https://www.devze.com 2023-04-08 04:20 出处:网络
Hello Guys can you help me solving my problem in reading xml. I\'m just new in xml. Here\'s the sample xml.

Hello Guys can you help me solving my problem in reading xml. I'm just new in xml. Here's the sample xml.

<Org>
    <Org ID="1">
        <OrgNum>1</OrgNum>
        <OrgName>sample1</OrgName>
    </Org>
    <Org 开发者_Python百科ID="2">
        <OrgNum>2</OrgNum>
        <OrgName>sample2</OrgName>
    </Org>
</Org>

I want to get only the OrgName with an Org ID = 2. Here's my sample code but it's read all the text. Help me plz..Tnx

string xml = Application.StartupPath + "\\OrgName.xml";
XmlDocument xmlDoc = new XmlDocument();
if (System.IO.File.Exists(xml))
{
    XmlTextReader textReader = new XmlTextReader(xml);
    textReader.Read();
    while (textReader.Read())
    {
        XmlNodeType nType = textReader.NodeType;
        if (nType == XmlNodeType.Text)
        {
            MessageBox.Show(textReader.Value);
        }
    }
}


A simple way to do it with linq:

 var doc = XDocument.Load(Application.StartupPath + "\\OrgName.xml");
 var result = doc.Root.Elements("Org").Where(x=>x.Attribute("id").ToString()=="2");


Maybe your life gets a lot easier if you start using tools like xdocument, xmldocument and xpath


If you want to use the classic .net Xml object model, you could try this:

    string xml = Application.StartupPath + "\\OrgName.xml";
    XmlDocument xmlDoc = new XmlDocument();
    if (System.IO.File.Exists(xml))
    {
       xmlDoc.Load(xml);
       XmlElement root = xmlDoc.DocumentElement;
       string orgName = root.SelectSingleNode(@"descendant::Org[@ID='1']/OrgName").InnerText;
       MessageBox.Show(orgName);
    }
0

精彩评论

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

关注公众号