简体   繁体   中英

C# and XML: Why is XMLNS attirubute set to all child nodes?

Here is what I have attempted: Creating elements:

            XmlNode xHeader = xDoc.CreateElement("Customer");
            XmlNode xCustomerID = xDoc.CreateElement("Customer_ID", strListName);
            XmlNode xName = xDoc.CreateElement("Full_Name");
            XmlNode xEmail = xDoc.CreateElement("Email");
            XmlNode xHomeAddress = xDoc.CreateElement("Home_Address");
            XmlNode xMobileNumber = xDoc.CreateElement("Mobile_Number");  

Appending nodes to document.

           xDoc.DocumentElement.AppendChild(xHeader);
            xHeader.AppendChild(xCustomerID);
            xCustomerID.AppendChild(xEmail);
            xCustomerID.AppendChild(xHomeAddress);
            xCustomerID.AppendChild(xMobileNumber);

This is what the is generated in the XML. http://pastebin.com/dNs8Ueiw I want there to be no xmlns = "" in the child nodes of Customer_ID.

If you want XML of:

<Customer_ID xmlns="a">
  <Email>
  </Email>
  <Home_Address>
  </Home_Address>
  <Mobile_Number>
  </Mobile_Number>
</Customer_ID>

... then you need to make sure your Email , Home_Address and Mobile_Number elements are all in the same namespace as your Customer_ID element:

XmlNode xCustomerID = xDoc.CreateElement("Customer_ID", strListName);
XmlNode xEmail = xDoc.CreateElement("Email", strListName);
XmlNode xHomeAddress = xDoc.CreateElement("Home_Address", strListName);
XmlNode xMobileNumber = xDoc.CreateElement("Mobile_Number", strListName); 

Basically you're seeing the result of namespace defaulting - unless an xmlns=... is specified for an element, it inherits the namespace of its parent.

(Also note that if you can, you should use LINQ to XML - it's a much more pleasant XML API, with nicer namespace handling.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM