Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

c# - Adding a prefix to an xml node

Current File Format

<Folio>
<Node1>Value1</Node1>
<Node2>Value2</Node2>
<Node3>Value3</Node3>
</Folio>

Desired Output

<vs:Folio>
<vs:Node1>Value1</vs:Node1>
<vs:Node2>Value2</vs:Node2>
<vs:Node3>Value3</vs:Node3>
</vs:Folio>

I am using XmlElement and XmlDocument to add the prefix to the child Node element and I'm unable to accomplish it. I would be really grateful if someone could give me the right push in the right direction.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are trying to add namespace to the elements after loading the xml document then it is not possible.

From MSDN:

You cannot add, modify, or delete an XML namespace definition in an instance of an XML document after the document has been loaded into the XML Document Object Model (XMLDOM) parser. The XML nodes that are used to represent data in the XML document are created when the document is loaded into the XMLDOM parser. These nodes are permanently bound to their XML namespace attributes when they are created. Therefore, the empty XML namespace declaration (xmlns = "") is appended to the child nodes of these nodes to preserve the default XML namespace attribute of these nodes.

However you can load the input, read each element and write it to another document (or in-memory) which has the namespace set. Below is the code that parses the string xml, creates a new xml element along with namespace prefix and namespace.

            String xmlWithoutNamespace =
                @"<Folio><Node1>Value1</Node1><Node2>Value2</Node2><Node3>Value3</Node3></Folio>";
            String prefix ="vs";
            String testNamespace = "http://www.testnamespace/vs/";
            XmlDocument xmlDocument = new XmlDocument();

            XElement folio = XElement.Parse(xmlWithoutNamespace);
            XmlElement folioNode = xmlDocument.CreateElement(prefix, folio.Name.LocalName, testNamespace);

            var nodes = from node in folio.Elements()
                        select node;

            foreach (XElement item in nodes)
            {
                var node = xmlDocument.CreateElement(prefix, item.Name.ToString(), testNamespace);
                node.InnerText = item.Value;
                folioNode.AppendChild(node);
            }

            xmlDocument.AppendChild(folioNode);

xmlDocument now contains the xml with each node prefixed with vs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...