在c#中从XML文件中读取某些值

时间:2012-04-27 00:15:15

标签: c# xml c#-4.0 linq-to-xml

我正在尝试从我的XML文件中读取一些数据

姓名/名称/ trckid

  • 1)例如,从我想要的下面粘贴的xml文件中 读取名称/名称/ trckid
       例如:trckid = FF7eb01f7-7985-47b1-8f8c-a0e92395d00f

  • 2)以及名称/名称/文件/文件/ uri,其中formatCode =“2001”
       例如结果字符串:uri = http://cont.catalog.address.xyz.com/e2/ds/9b660964.jpg

这是我的示例XML文件

<?xml version="1.0" encoding="utf-8"?>
<Names tracking="trckids" execTime="0" xmlns="urn:schemas-microsoft-com:address:catalog">
    <Name xmlns="urn:schemas-microsoft-com:address:catalog" publishState="Published" lcid="1033" options="0" version="65" filterFlags="32687">
        <trckid ref="5ofol35" seoMetaData="/xyz/gpscatalog/">FF7eb01f7-7985-47b1-8f8c-a0e92395d00f</trckid>
        <providerId>Test0_2286326_304163829</providerId>
        <files>
            <file formatCode="2001" gpsFileId="9B660964-1626-466C-8359-F036506D8769" height="102" width="136" fileHash="4a4bcceb08b4ccdd16a958e8687c9588">
                <uri>http://cont.catalog.address.xyz.com/e2/ds/9b660964-1626-466c-8359-f036506d8769.jpg</uri>
            </file>
            <file formatCode="2007">
                <uri>http://img1.catalog.address.xyz.com/image.aspx?uuid=d7eb01f7-7985-47b1-8f8c-a0e92395d00f&amp;w=136&amp;h=102</uri>
            </file>
            <file formatCode="2200" gpsFileId="6C34F723-D798-4DA8-AEE4-0442C239D3A0" fileSize="311469" height="180" width="320"                                                                             sourceFileHash="6ea74770f622e3e0dc9cf5e229c7de7f">
                <uri>http://cont.catalog.address.xyz.com/e2/ds/0909a015-4b6a-4574-be63-c2facd527b9f_0.xml</uri>
            </file>
        </files>
    </Name>
   <Name xmlns="urn:schemas-microsoft-com:address:catalog" publishState="Published" lcid="1033" options="0" version="65" filterFlags="32687">
        <trckid ref="5ofol20" seoMetaData="/xyz/gpscatalog/">FF9eb01f7-7985-47b1-8f8c-a0e92395d00f</trckid>
        <providerId>Test1TheLorax_2286326_304163829</providerId>
        <files>
            <file formatCode="2001" gpsFileId="9B660964-1626-466C-8359-F036506D8769" height="102" width="136" fileHash="4a4bcceb08b4ccdd16a958e8687c9588">
                <uri>http://cont.catalog.address.xyz.com/e2/ds/9b660964-1626-466c-8359-f036506d8769.jpg</uri>
            </file>
            <file formatCode="2007">
                <uri>http://img1.catalog.address.xyz.com/image.aspx?uuid=d7eb01f7-7985-47b1-8f8c-a0e92395d00f&amp;w=136&amp;h=102</uri>
            </file>
            <file formatCode="2200" gpsFileId="6C34F723-D798-4DA8-AEE4-0442C239D3A0" fileSize="311469" height="180" width="320"                                                                             sourceFileHash="6ea74770f622e3e0dc9cf5e229c7de7f">
                <uri>http://cont.catalog.address.xyz.com/e2/ds/0909a015-4b6a-4574-be63-c2facd527b9f_0.xml</uri>
            </file>
        </files>
    </Name>
</Names>

我尝试使用下面给出的一段代码

      XDocument xdoc = XDocument.Parse(xmlstring);
            XNamespace ns = xdoc.Root.GetDefaultNamespace();  // "urn:schemas-microsoft-com:msnvideo:catalog";
            IEnumerable<XElement> names = xdoc.Descendants(ns + "name");
   foreach (XElement name in names)
            {


                 rssFeedItems.Add(new Adressses
                    {
                    trackid=  Convert.ToString(name.Element(ns + "trackid").Value),
                    providerID= Convert.ToString(name.Element(ns + "provideid").Value),

                    imageUri = Convert.ToString(name.Element(ns + "uri").Value)
                    });

            }        
  Here  am able to read first two items ,ie, trackid and providerID ,but not the image uri

我需要读取与名称/名称/文件/文件@ formatcode [2001] / uri

匹配的uri

类似

 imageUri = Convert.ToString(name.Element(ns + "Names/Name/files/file@formatcode[2001]/uri").Value)

但这不起作用。请帮忙

3 个答案:

答案 0 :(得分:2)

首先,你的xml无效。结束标记应如下</Names>而不是<Names/>

其次,您必须添加名称空间声明。像这样:

    XNamespace cat = "urn:schemas-microsoft-com:address:catalog";
    XNamespace add = "urn:schemas-microsoft-com:msnvideo:address";
    XDocument doc = XDocument.Parse(xdata);
    var firstTrck = doc.Element(cat + "Names").Elements(add + "Name").First().Element(add + "trckid");
    var val = firstTrck.Value;

另外值得注意的是,请注意如何在元素/元素上追加以确保您正在寻找一个或多个元素。

以下是迭代元素集的方法:

        XNamespace cat = "urn:schemas-microsoft-com:address:catalog";
        XNamespace add = "urn:schemas-microsoft-com:msnvideo:address";
        XDocument doc = XDocument.Parse(xdata);

        var xNames = doc.Element(cat + "Names").Elements(add + "Name");
        foreach (var xName in xNames)
        {
            var trackingId = xName.Element(add + "trckid").Value;

            var xFiles = xName.Element(add + "files").Elements(add + "file").Where(xe => (string)xe.Attribute("formatCode") == "2001");
            foreach (var xFile in xFiles)
            {
                var uri = xFile.Element(add + "uri").Value;
            }
        }

请注意,在调试时,集合中只会出现一个“Name”元素。这是因为xmlns声明与每个声明不匹配。

答案 1 :(得分:1)

我认为这会做你想要的。

XmlDocument doc = new XmlDocument();
WebClient webClient = new WebClient();
string xmlstring = webClient.DownloadString(url);
doc.LoadXml(xmlstring);
XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("ns", "urn:schemas-microsoft-com:address:catalog");
foreach (XmlNode n in doc.SelectNodes("/ns:Names/ns:Name/ns:trckid/@ref", nsMgr))
{
    Console.WriteLine(String.Format("trckid: {0}", n.InnerText));
}
foreach (XmlNode n in doc.SelectNodes("/ns:Names/ns:Name/ns:files/ns:file[@formatCode='2001']/ns:uri", nsMgr))
{
    Console.WriteLine(String.Format("uri: {0}", n.InnerText));
}

答案 2 :(得分:-1)

为什么不将每行读入字符串数组,然后搜索包含您要查找的前缀的行。剥去它的正面和背面并将其存储在一个变量中..那对你有用吗?