“The ':' character, hexadecimal value 0x3A, cannot be included in a name”

前端 未结 1 1036
南方客
南方客 2021-01-18 08:19

I have a code which will read some xml file(s). I tried different ways to solve this problem, but couldn\'t. Also I tried to code like this:

Namespace my = \         


        
1条回答
  •  情歌与酒
    2021-01-18 09:04

    The code Element("my:" + "Egitim_Bilgileri") is the same as Element("my:Egitim_Bilgileri") which is taken to mean the element named "my:Egitim_Bilgileri" in the default namespace (there is an implicit conversion from string to XName).

    However, : is invalid in an element name (outside of the namespace separation) and thus will result in a run-time exception.

    Instead, the code should be Element(my + "Egitim_Bilgileri") where my is an XNamespace object. The XNamespace object's + operator, when given a string as the second operand, results in an XName object that can then be used with the Element(XName) method.

    For instance:

    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);
    

    Happy coding... and condolences for having to deal with InfoPath :)


    I prefer to use XPath in most cases. Among other things it allows easily selecting nested nodes and avoids having to "check for null" each level as may be required with node.Element(x).Element(y) constructs.

    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);
    

    0 讨论(0)
提交回复
热议问题