简体   繁体   English

C#省略节点XML

[英]C# omitting nodes XML

I have an XML document that is written with this algorithm: 我有一个用此算法编写的XML文档:

public XMLmethod(){
string[] nodes = { "node1", "node2", "node3" }; //etc etc

XmlTextWriter writer= new XmlTextWriter("file.xml", Encoding.UTF8);

writer.WriteStartDocument();
writer.WriteStartElement("root");

foreach (string node in nodes){
writer.WriteStartElement(s);
writer.WriteEndElement();
XMLmethod()}

writer.WriteEndElement();
writer.WriteEndDocument();
}

The above is a simplified version. 上面是简化版本。 However, I want to be able to filter out some nodes before printing them to xml. 但是,我希望能够在将某些节点打印到xml之前将其过滤掉。

For example: 例如:

<root>
 <node1>
  <node2> </node2>
  <node3> </node3>
 </node1>
<root>

Say I wanted to filter <node1> </node1> 说我想过滤<node1> </node1>

So it would look like this 所以看起来像这样

<root>
 <node2></node2>
 <node3></node3>
</root>

so it would still want to print the children <node2></node2> and <node3></node3> 因此它仍然希望打印子<node2></node2><node3></node3>

I thought about using an if statement like: 我考虑过使用if语句,例如:

foreach (string node in nodes){
if(node == "node1"){}
else{
writer.WriteStartElement(node);
writer.WriteEndElement();
XMLmethod()}
}

this successfully doesn't print <node1>/<node1> but it also stops it from printing the children nodes. 此操作不会成功打印<node1>/<node1>但也会阻止其打印子节点。 Any idea how I can go about doing this? 知道我该怎么做吗?

If you have a class, such as Foo below, and you want to omit one or more properties when serialzing it using the .Net XmlSerializer , use the XmlIgnore attribute: 如果您有一个类,例如下面的Foo,并且想要在使用.Net XmlSerializer进行序列化时忽略一个或多个属性,请使用XmlIgnore属性:

public class Foo
{
    [XmlIngore]
    public string Node1 { get; set; }
    public string Node2 { get; set; }
    public string Node3 { get; set; }
}

This will cause XmlSerializer to only output <node2> and <node3> . 这将导致XmlSerializer仅输出<node2><node3>

If the code that you have posted works, you could probably try removing the items from the list before iterating, for example 如果您发布的代码有效,则可以尝试在迭代之前从列表中删除项目,例如

nodes.Remove("node1");

foreach (string node in nodes)
{
}

But, it's unclear from your code sample why you would want to do this. 但是,从代码示例中尚不清楚为什么要执行此操作。 XML documents are nested in a hierarchical manner because it allows for relationships and semantic context between the elements. XML文档以分层的方式嵌套,因为它允许元素之间的关系和语义上下文。 Removing parent nodes may reduce the usability of the XML you are producing. 删除父节点可能会降低所生成的XML的可用性。

For example, if the document was 例如,如果文档是

<People>
  <Person>
    <FirstName>Max</FirstName>
    <LastName>Smart</LastName>
  </Person>
</People>

It would make no sense to just remove the <Person> tag, and output FirstName and LastName on their own. 仅删除<Person>标记并自行输出FirstNameLastName是没有意义的。

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

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