-1

这是我来自文件的 XML 数据

<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml" />
<item id="W000Title" href="000Title.html" media-type="application/xhtml+xml" />
<item id="W01MB154" href="01MB154.html" media-type="application/xhtml+xml" />
<item id="WTOC" href="TOC.html" media-type="application/xhtml+xml" />

我想在 Store 应用程序中使用 C# 获取元素值。我得到了价值观,但这不是正确的方法,我无法进行下一步。

    string fileContents3 = await FileIO.ReadTextAsync(file);
    xmlDoc1.LoadXml(fileContents3);
    XmlNodeList item = xmlDoc1.GetElementsByTagName("item");
    for (uint k = 0; k < item.Length; k++)
    {
        XmlElement ele1 = (XmlElement)item.Item(k);
        var attri1 = ele1.Attributes;
        var attrilist1 = attri1.ToArray();
        for (int l = 0; l < attrilist1.Length; l++)
        {
            if (attrilist1[l].NodeName == "id")
            {

                    ids2 = attrilist1[0].NodeValue.ToString();
                    ids3 = attrilist1[1].NodeValue.ToString();
            }
        } 
   }

而不是这种方式,我想知道任何方法来获取属性“id”的元素值

4

3 回答 3

0

如果要获取XmlNode对象的属性值,可以使用此函数:

    public static string GetAttributeValue(XmlNode node, string attributeName)
    {
        XmlAttribute attr = node.Attributes[attributeName];
        return (attr == null) ? null : attr.Value;
    }
于 2013-05-20T12:04:30.797 回答
0
string fileContents3 = await FileIO.ReadTextAsync(file);
xmlDoc1.LoadXml(fileContents3);
XmlNodeList item = xmlDoc1.GetElementsByTagName("item");
        for (uint k = 0; k < item.Length; k++)
        {
            XmlElement ele1 = (XmlElement)item.Item(k);
            string foo = ele1.Attributes[0].NodeValue.ToString();
        }

I simplified your code a little. Hope this will help you. I assume that the id Attribute is always on first Position (Index 0).

于 2013-05-20T17:52:24.890 回答
0

如果你需要使用 XPath,你可以使用如下,

      XmlDocument document = new XmlDocument();
        document.Load(@"c:\users\saravanan\documents\visual studio 2010\Projects\test\test\XMLFile1.xml");

        XmlNodeList itemNodes = document.SelectNodes("//item");

        foreach (XmlElement node in itemNodes)
        {
            if (node.Attributes.Count > 0)
            {
                if (node.HasAttribute("id"))
                {
                    Console.Write(node.Attributes["id"]);
                }

            }
        }

        var itemNodeswithAttribute = document.SelectNodes("//item[href=toc.ncx]");

        itemNodeswithAttribute = document.SelectNodes("//item[@href='toc.ncx']");
于 2013-05-20T12:23:29.390 回答