“':'字符,十六进制值0x3A,不能包含在名称中”

时间:2011-08-27 07:55:59

标签: c# xml linq-to-xml infopath

我有一个代码可以读取一些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文件的路径:

<my:Egitim_Bilgileri>
        <my:egitimler_sap>
            <my:sap_eduname></my:sap_eduname>
            <my:sap_edufaculty></my:sap_edufaculty>
            <my:sap_eduprofession></my:sap_eduprofession>
            <my:sap_diplomno></my:sap_diplomno>
            <my:sap_edulevel></my:sap_edulevel>
            <my:sap_edustartdate xsi:nil="true"></my:sap_edustartdate>
            <my:sap_eduenddate xsi:nil="true"></my:sap_eduenddate>
        </my:egitimler_sap>
    </my:Egitim_Bilgileri>

这是我在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"

1 个答案:

答案 0 :(得分:12)

代码Element("my:" + "Egitim_Bilgileri")Element("my:Egitim_Bilgileri")相同,用于表示默认命名空间中名为“my:Egitim_Bilgileri”的元素 (有一个implicit conversion from string to XName)。

但是,: 在元素名称中无效(在命名空间分隔之外),因此会导致运行时异常。

相反,代码应为Element(my + "Egitim_Bilgileri"),其中myXNamespace个对象。当给定一个字符串作为第二个操作数时,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);