如何在XML C#中的另一个标签中生成标签?
我有一个类似于下面的类文件:
public class property : root
{
public string languages { get; set; }
}
我正在尝试生成 xml
如下:
最终输出:
<root>
<property>
--other properties
<languages>
<en>This is English Languages description</en>
<fr></fr>
</languages>
</property>
</root>
这就是我尝试生成&lt; lanking&gt; gt;在
private string GenerateLanguageTag(IList<Languages> languages)
{
string lang = string.Empty;
foreach (var item in languages)
{
lang += "<" + item.IsoLanguageCode + ">" + item.Description + "</" + item.IsoLanguageCode + ">";
}
return lang;
}
<root>
<property>
--other properties
<languages><en>This is English Languages description
</en><fr></fr></languages>
</property>
</root>
root root = GetData(data);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(root));
using (StringWriter xmlWriter = new StringWriter())
{
xmlSerializer.Serialize(xmlWriter, root);
value = xmlWriter.ToString();
value = value.Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
value = value.Replace(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
value = value.Replace("utf-16", "ISO-8859-1");
if (File.Exists(filePath))
{
var document = XDocument.Parse(value);
document.Save(filePath);
}
}
&lt;语言中的其他语言&gt;&lt;/语言&gt;
是根据我们在数据库中的语言动态生成的。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
而不是将
语言
声明为字符串
,将其声明为XELEMENT
,并用语言的孩子属性应插入其父母&lt; property&gt;
元素。因此,您的数据模型应该看起来像:您将构造模型如下:
注:
xmlanyelementAttribute
应将其应用于类型代码> XMLNODE (或同一数组),但实际上它也适用于类型XElement
的属性。由于linq to-xml比旧的xmldocument
api更容易使用,因此我建议使用它。在您的问题中,您显示
属性
作为root
的子类。为了获得所需的嵌套,它应该是由root
包含的单独类,而不是root> root
的子类。消除
XSI
和XSD
namespaces(无需进行字符串替换)请参见 XMLSerializer:删除不必要的XSI和XSD名称空间 。。演示小提琴在这里。
Rather than declaring
languages
as astring
, declare it as anXElement
and mark it with[XmlAnyElement("languages")]
. This informs the serializer that the children of thelanguages
property should be inserted as children of their parent<property>
element. Thus your data model should look like:And you would construct your model as follows:
Notes:
The documentation for
XmlAnyElementAttribute
indicates it should be applied to properties of typeXmlElement
orXmlNode
(or arrays of the same), but in fact it works for properties of typeXElement
as well. Since LINQ-to-XML is easier to work with than the oldXmlDocument
API, I suggest using it instead.In your question you show
property
as a subclass ofroot
. In order to get the nesting you require, it should be a separate class contained byroot
, not a subclass ofroot
.To eliminate the
xsi
andxsd
namespaces (without needing to do a string replacement) see XmlSerializer: remove unnecessary xsi and xsd namespaces.Demo fiddle here.
使用XML Linq:
Using Xml Linq :