“’:’字符,hex值0x3A,不能包含在名称中”
我有一个代码,它将读取一些xml文件。 我尝试了不同的方法来解决这个问题,但不能。 我也尝试这样编码:
Namespace my = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-01-11T08:31:30"; XElement myEgitimBilgileri = XDocument.Load(@"C:\25036077.xml").Element("my:"+ "Egitim_Bilgileri");
但一直都是同样的错误。 这是原件:
private void button2_Click(object sender, EventArgs e) { XElement myEgitimBilgileri = XDocument.Load(@"C:\25036077.xml").Element("my:Egitim_Bilgileri"); if (myEgitimBilgileri != null) { foreach (XElement element in myEgitimBilgileri.Elements()) { Console.WriteLine("Name: {0}\tValue: {1}", element.Name, element.Value.Trim()); } } Console.Read(); }
这是我的xml文件的路径:
这是我在XML中的命名空间的路径
xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-01-11T08:31:30" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-01-23T00:43:17"
代码Element("my:" + "Egitim_Bilgileri")
与Element("my:Egitim_Bilgileri")
,后者表示默认命名空间中 名为 “my:Egitim_Bilgileri”的元素( 字符串是隐式转换)到XName )。
但是, :
元素名称(名称空间分隔之外)无效 ,因此将导致运行时exception。
相反,代码应该是Element(my + "Egitim_Bilgileri")
,其中my
是XNamespace对象。 当给定字符串作为第二个操作数时,XNamespace对象的+
运算符会生成一个XName对象,然后可以与Element(XName)
方法一起使用。
例如:
XNamespace my = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-01-11T08:31:30"; XDocument doc = XDocument.Load(@"C:\25036077.xml"); // The following variable/assignment can be omitted, // it is to show the + operator of XNamespace and how it results in XName XName nodeName = my + "Egitim_Bilgileri"; XElement myEgitimBilgileri = doc.Element(nodeName);
快乐的编码……以及对必须处理InfoPath的哀悼:)
在大多数情况下,我更喜欢使用XPath。 除此之外,它还允许轻松选择嵌套节点,并避免必须使用node.Element(x).Element(y)
构造所需的每个级别“检查null”。
using System.Xml.XPath; // for XPathSelectElement extension method XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable()); ns.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-01-11T08:31:30") // Note that there is no XName object. Instead the XPath string is parsed // and namespace resolution happens via the XmlNamespaceManager XElement myEgitimBilgileri = doc.XPathSelectElement("/my:myFields/my:Egitim_Bilgileri", ns);