繁体   English   中英

xmldocument将值显示为xml中的value属性

[英]Xmldocument show value as value attribute in xml

xmldocument为我生成所有条目,如下所示

<type>document</type>

我希望它像这样生成

<type value = "document"></type>

有没有简单的方法可以做到这一点?

只是为了添加更多详细信息,我有一个json,它将使用JsonConvert.DeserializeXmlNode将其从json转换为xml。

当我使用此api进行转换时,我会得到这样的价值-

<type>document</type>

我希望它是-

<type value = "document"></type>

这是生成属性的示例代码。

XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateNode(XmlNodeType.Element, "type", "");
XmlAttribute attr = doc.CreateAttribute("value");
attr.Value = "Document";
node.Attributes.Append(attr);
doc.AppendChild(node);
var outputString = doc.InnerXml;

我更喜欢用于XML创建的XML Linq类。 编写和阅读要容易得多。 您可以将其与“使用System.Xml.Linq;”绑定。 现在,您可以在具有“新XAttribute”的元素中创建属性。

这是一个小例子:

        //build base
        XNamespace myNs = "http://www.w3.org/2001/XMLSchema-instance";
        XDocument myDoc = new XDocument(
            new XDeclaration("1.0", "UTF-8", null),
            new XElement("newDocument",
                new XAttribute(XNamespace.Xmlns + "xsi", myNs),
                new XAttribute(myNs + "noNamespaceSchemaLocation", "ArchiveDocument.xsd"),
                new XElement("document",
                    new XAttribute("instanceDate", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")),
                    new XElement("attribute",
                        new XAttribute("attributeDefinitionId", "Belegart"),
                        new XElement("value", reportType)),
                    new XElement("attribute",
                        new XAttribute("attributeDefinitionId", "Date"),
                        new XElement("value", Date.ToString("yyyyMMdd"))),
                    new XElement("attribute",
                        new XAttribute("attributeDefinitionId", "Kalenderjahr"),
                        new XElement("value", Date.ToString("yyyy"))),
                    new XElement("attribute",
                        new XAttribute("attributeDefinitionId", "Kalendermonat"),
                        new XElement("value", Date.Month.ToString())),
                    new XElement("attribute",
                        new XAttribute("attributeDefinitionId", "Mitglieds_Nummer"),
                        new XElement("value", partnerId.ToString())))));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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