我怎样才能在XML节点通过ID? [英] How can I get a node by id in XML?

查看:172
本文介绍了我怎样才能在XML节点通过ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建使用XML是通过ID语言翻译

I am creating a language translation using XML by 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>

身后code:

Code behind:

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'

这code不起作用,的XmlNodeList 为null。
我怎样才能获得内容Word1_French?

This code doesn't work, xmlNodeList is null.
How can I get the content Word1_French?

推荐答案

检查的上XmlDocument.GetElementById方法 MSDN文档:

Check the MSDN documentation on XmlDocument.GetElementById Method:

DOM实现必须有一个定义信息这   属性是ID类型。虽然ID类型的属性可   在任一XSD模式或DTD定义的,这个版本的产品   只支持那些在DTD中定义。 属性名称为ID是   不是类型ID,除非这样在DTD定义。实现它   未知属性是否是ID类型,预计   返回null。

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文件来指定你所说的'身份证'的意思。如果你不想这样做,用的选择方法与的XPath

In fact, you have to modify your XML file for specifying what you mean by 'ID'. If you don't want to do that, use a select method with an 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'

这篇关于我怎样才能在XML节点通过ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆