XElement namespaces (How to?)

XElement namespaces (How to?)

Asked on January 9, 2019 in XML.
Add Comment


  • 5 Answer(s)

    LINQ to XML:

    XNamespace ns = "sphinx";
    XElement element = new XElement(ns + "docset");
    

         Else to make the “alias” work correctly to make it look like the below example,

    XNamespace ns = "http://url/for/sphinx";
    XElement element = new XElement("container",
      new XAttribute(XNamespace.Xmlns + "sphinx", ns),
      new XElement(ns + "docset",
        new XElement(ns + "schema"),
          new XElement(ns + "field", new XAttribute("name", "subject")),
          new XElement(ns + "field", new XAttribute("name", "content")),
          new XElement(ns + "attr",
                new XAttribute("name", "published"),
                new XAttribute("type", "timestamp"))));
    

         It produces:

    <container xmlns:sphinx="http://url/for/sphinx">
      <sphinx:docset>
        <sphinx:schema />
        <sphinx:field name="subject" />
        <sphinx:field name="content" />
        <sphinx:attr name="published" type="timestamp" />
      </sphinx:docset>
    </container>
    
    Answered on January 9, 2019.
    Add Comment

         Read the namespace of the users document and use it in queries like,

    XDocument xml = XDocument.Load(address);
    XNamespace ns = xml.Root.Name.Namespace;
    foreach (XElement el in xml.Descendants(ns + "whateverYourElementNameIs"))
       //do stuff
    
    Answered on January 9, 2019.
    Add Comment
    <sphinx:docset>
      <sphinx:schema>
        <sphinx:field name="subject"/>
        <sphinx:field name="content"/>
        <sphinx:attr name="published" type="timestamp"/>
     </sphinx:schema>
    Answered on February 25, 2019.
    Add Comment
    XNamespace ns = "http://url/for/sphinx";
    XElement element = new XElement("container",
        new XAttribute(XNamespace.Xmlns + "sphinx", ns),
        new XElement(ns + "docset",
            new XElement(ns + "schema"),
                new XElement(ns + "field", new XAttribute("name", "subject")),
                new XElement(ns + "field", new XAttribute("name", "content")),
                new XElement(ns + "attr", 
                             new XAttribute("name", "published"),
                             new XAttribute("type", "timestamp"))));
    Answered on February 25, 2019.
    Add Comment
    <container xmlns:sphinx="http://url/for/sphinx">
      <sphinx:docset>
        <sphinx:schema />
        <sphinx:field name="subject" />
        <sphinx:field name="content" />
        <sphinx:attr name="published" type="timestamp" />
      </sphinx:docset>
    </container>
    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.