c# - 如何通过 XML 中的 id 获取节点?

标签 c# .net xml parsing

我正在通过 id 使用 XML 创建语言翻译

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?

最佳答案

检查 MSDN documentation on XmlDocument.GetElementById Method :

The DOM implementation must have information which defines which attributes are of type ID. Although attributes of type ID can be defined in either XSD schemas or DTDs, this version of the product only supports those defined in DTDs. Attributes with the name "ID" are not of type ID unless so defined in the DTD. Implementations where it is unknown whether the attributes are of type ID are expected to 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'

关于c# - 如何通过 XML 中的 id 获取节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19786770/

相关文章:

c# - 收集崩溃数据的最佳方法是什么?

c# - 按用户评分对产品进行排序/排名的公式

.net - 如何从 wcf 的响应中删除 null DataMember 属性

xml - 这个 "PCDATA invalid Char value 11"错误是什么?

c# - 无法安装或运行应用程序 - System.Windows.Interactivity 版本 4.0.0.0

c# - 在不同的String字典上做benchmark,普通的比较快,不知道为什么

.net - .NET Regex 类的运算符优先级在哪里记录?

Android Studio 2.2 Gridlayout 不工作

java - 使用 java 解析器删除 XML 节点

c# - C# 中的 Quickbase API 示例