简体   繁体   中英

C# XAttribute with whitespaces

How can I have whitespaces on XAttribute, here is my code snippet:

new XElement("SubstitutionAttribute", new XAttribute("SubNetwork Group",subNetBox.Text))

What I am trying to achieve in xml:

<SubstitutionAttribute name="SubNetwork Group" value="Something" />

Best regards,

Hugo

The reason your example is failing is because the constructor for XAttribute expects the name of the attribute and its value.

So with new XElement("SubstitutionAttribute", new XAttribute("SubNetwork Group",subNetBox.Text)) you are acutally declaring only one attribute with the name "Subnetwork Group" and the value subNetBox.Text ( <SubstitutionAttribute SubNetwork Group="Something" /> ). This is invalid XML as you can't have spaces in an attribute name.

What I think you are trying to do should be done with two attributes - one called name and the other called value :

new XElement("SubstitutionAttribute", 
    new XAttribute("name", "SubNetwork Group"), 
    new XAttribute("value", subNetBox.Text));

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