如何在XML中通过id获取节点?

时间:2013-11-05 10:29:31

标签: c# .net xml parsing

我正在使用ID

创建语言翻译

XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <word id="1">Word1_English</word>
    <word id="2">Word2_English</word>
    <word id="3">Word3_English</word>

    <word id="10001">Word1_French</word>
    <word id="10002">Word2_French</word>
    <word id="10003">Word3_French</word>

    <word id="20001">Word1_Chinese</word>
    <word id="20002">Word2_Chinese</word>
    <word id="20003">Word3_Chinese</word>
</root>

代码背后:

XmlDocument xmlDocument;
FileInfo fileInfo;
XmlNodeList xmlNodeList;

string xPath = "D:\XML\LanguagePack.xml";
fileInfo = new FileInfo(xPath);
xmlDocument = new XmlDocument();
xmlDocument.Load(fileInfo.FullName);

xmlNodeList = xmlDocument.GetElementById("10001");
return xmlNodeList[0].InnerText; //should return 'Word1_French'

此代码不起作用,xmlNodeList为空。
如何获取Word1_French的内容?

2 个答案:

答案 0 :(得分:6)

检查MSDN documentation on XmlDocument.GetElementById Method

  

DOM实现必须具有定义哪些信息   属性是ID类型。虽然ID类型的属性可以   在XSD架构或DTD中定义,此版本的产品   仅支持DTD中定义的那些。 名称为“ID”的属性为   除非在DTD中如此定义,否则不是ID类型。它的实现   不知道属性是否属于ID类型   return null。

实际上,您必须修改XML文件以指定“ID”的含义。如果您不想这样做,请使用select方法和XPath

所以你需要改为:

string filePath = "D:\\XML\\LanguagePack.xml";
var fileInfo = new FileInfo(filePath);
var xmlDocument = new XmlDocument();
xmlDocument.Load(fileInfo.FullName);

var node = xmlDocument.SelectSingleNode("//*[@id='10001']");
return node.InnerText; // return 'Word1_French'

答案 1 :(得分:2)

我建议你使用LINQ to XML来解析XML。它有很好的强类型API。通过整数id获取字符串单词(需要 System.Xml.Linq 名称空间):

var xdoc = XDocument.Load(filePath);
string word = xdoc.Root.Elements()
                  .Where(w => (int)w.Attribute("id") == id)
                  .Select(w => (string)w)
                  .FirstOrDefault();

甚至更少的XPath代码(需要 System.Xml.XPath 命名空间):

string word = (string)xdoc.XPathSelectElement("//word[@id='10001']");
相关问题